【问题标题】:Printing text from BeautifulSoup object, excluding certain tags? [Python 2.7]从 BeautifulSoup 对象打印文本,不包括某些标签? [Python 2.7]
【发布时间】:2013-09-11 21:31:05
【问题描述】:

如果你有一个 BS 对象,例如:

>>> print soup
<div>
   Peter Griffin
   <br>
   Lois Griffin
   <br>
   Chris Griffin
   <br>
   <div> Meg Griffin </div>
   <br>
   Stewie Griffin
   <br>
<div>

您如何打印soup.text,不包括内部&lt;div&gt; 内的所有内容?

我想要的输出是:

>>> print <clever_code>
Peter Griffin
Lois Griffin
Chris Griffin
Stewie Griffin

干杯!

【问题讨论】:

    标签: python python-2.7 beautifulsoup


    【解决方案1】:

    一种选择可能是删除内部&lt;div&gt; 标记并在删除多余空格后打印soup 的文本:

    for tag in soup.select('div div'):
        tag.clear()
    print('\n'.join(re.split(r'\s*\n+\s*', soup.text.strip())))
    

    它产生:

    Peter Griffin
    Lois Griffin
    Chris Griffin
    Stewie Griffin
    

    【讨论】:

    • +1 在 BeautifulSoup 参数中回答我的问题,虽然我真的不认为这里需要Regex。谢谢!
    • @Jacob-IT:regex 用于折叠字符串之间的空格
    【解决方案2】:

    使用基于 Python 标准库中的模块构建的类...

    from HTMLParser import HTMLParser
    
    class HTML_tag_stripper(HTMLParser):
        def __init__(self):
            self.reset()
            self.fed = []
        def handle_data(self, d):
            self.fed.append(d)
        def get_data(self):
            return ''.join(self.fed)
    
    def strip_tags(html):
        s = HTML_tag_stripper()
        s.feed(html)
        return s.get_data()
    
    >>> print strip_tags( str(soup) )
    

    【讨论】:

    • 啊..这很有意义,现在我看看它。谢谢,只是出于好奇,BS 是否有本地方法来执行此任务?
    • 我不知道。此外,原生更好。 :)
    • 嗯......当我运行这段代码时,我得到一个错误:s.feed(html)File "C:\Python27\lib\HTMLParser.py", line 113, in feedself.rawdata = self.rawdata + dataTypeError: cannot concatenate 'str' and 'Tag' objects
    • 我刚刚测试没有错误,但你有一个真实的世界情况。您可能需要将某些内容投射到 str。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 2021-04-14
    相关资源
    最近更新 更多