在BeautifulSoup中查找标签和文本

时间:2011-08-07 21:00:30

标签: python html beautifulsoup

我在为BeautifulSoup制定一个findAll查询时遇到了一些麻烦,我会按照自己的意愿行事。以前,我使用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>标签。重要的是标签留在他们标记的文本周围 - 我不能让标签或文本出现乱序。

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

注意: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>.'