【问题标题】:Finding Tags And Text In BeautifulSoup在 BeautifulSoup 中查找标签和文本
【发布时间】:2011-08-07 21:00:30
【问题描述】:

我在为 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)) 来做到这一点。这很好用,直到我决定只保留&lt;a&gt; 标签,但去掉其余的标签。所以,给定最初的例子,我会得到这样的结果:

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 &lt;a&gt; 标签。重要的是标签要围绕在它们标记的文本周围——我不能让标签或文本出现乱序。

有什么想法吗?

【问题讨论】:

    标签: python html beautifulsoup


    【解决方案1】:

    注意:BeautifulSoup.findAll 是一个搜索 API。 findAll 的第一个命名参数name 可用于将搜索限制为给定的一组标签。仅使用一个findAll 不可能选择标签之间的所有文本并同时选择&lt;a&gt; 的文本和标签。所以我想出了以下解决方案。

    此解决方案依赖于导入的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 方法像列表一样导航解析树。只有当它是一个标签并且标签不是&lt;a&gt; 时,我们才会提取文本。否则我们会得到包含标签的整个字符串。这使用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>.'
    

    【讨论】:

    • 非常感谢!除了使用 findAll 方法之外,我对导航解析树不是很熟悉。
    猜你喜欢
    • 2013-01-11
    • 2018-10-11
    • 2017-05-04
    • 2016-01-10
    • 2020-03-08
    • 2019-10-08
    • 2019-10-31
    • 2012-11-04
    • 1970-01-01
    相关资源
    最近更新 更多