作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我在制定 findAll
时遇到了一些问题查询 BeautifulSoup 会做我想做的事。以前,我使用的是 findAll
仅从一些 html 中提取文本,基本上剥离所有标签。例如,如果我有:
<b>Cows</b> are being abducted by aliens according to the
<a href="www.washingtonpost.com>Washington Post</a>.
它将减少为:
Cows are being abducted by aliens according to the Washington Post.
我会使用 ''.join(html.findAll(text=True))
来做到这一点.这工作得很好,直到我决定只保留 <a>
标签,但去掉其余的标签。因此,根据最初的例子,我会这样结束:
Cows are being abducted by aliens according to the
<a href="www.washingtonpost.com>Washington Post</a>.
我最初认为以下方法可以解决问题:
''.join(html.findAll({'a':True}, text=True))
但是,这不起作用,因为 text=True
似乎表明它只会找到文本。我需要的是一些 OR 选项——我想找到文本 OR <a>
标签。标签保持在它们所标记的文本周围很重要 - 我不能让标签或文本出现乱序。
有什么想法吗?
最佳答案
注意:BeautifulSoup.findAll是一个搜索 API。 findAll
的第一个命名参数这是 name
可用于将搜索限制为一组给定的标签。只有一个 findAll
无法选择标签之间的所有文本,同时选择 <a>
的文本和标签.所以我想出了以下解决方案。
此解决方案取决于 BeautifulSoup.Tag
正在导入。
from BeautifulSoup import BeautifulSoup, Tag
soup = BeautifulSoup('<b>Cows</b> are being abducted by aliens according to the <a href="www.washingtonpost.com>Washington Post</a>.')
parsed_soup = ''
我们像使用 contents
的列表一样在解析树中导航方法。我们仅在文本是标签且标签不是 <a>
时提取文本.否则我们会得到包含标签的整个字符串。这使用 navigating the parse tree API .
for item in soup.contents:
if type(item) is Tag and u'a' != item.name:
parsed_soup += ''.join(item.findAll(text = True))
else:
parsed_soup += unicode(item)
保留文本的顺序。
>>> print parsed_soup
u'Cows are being abducted by aliens according to the <a href=\'"www.washingtonpost.com\'>Washington Post</a>.'
关于python - 在 BeautifulSoup 中查找标签和文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6975757/
我是一名优秀的程序员,十分优秀!