1

下面是一个用 beautifulsoup4 解析的简单 html 段,我希望提取顶级原始文本hello

mysoup = BeautifulSoup('<td>hello<script type="text/javascript">world</script></td>')

而且我尝试了几种直观的方法,但没有预期的结果:

mysoup.text            # u'helloworld'
mysoup.contents        # [<html><body><td>hello<script type="text/javascript">world</script></td></body></html>]
list(mysoup.strings)   # [u'hello ', u'world']

那么如何实现这个目标呢?

4

1 回答 1

0

首先,获取对td节点的引用。然后,遍历它的孩子,看看它们中的哪些是字符串

from bs4 import BeautifulSoup
mysoup = BeautifulSoup('<td>hello<script type="text/javascript">world</script></td>')
td = mysoup.find('td')
print [s for s in td.children if isinstance(s, basestring)]
于 2015-04-16T08:03:01.537 回答