【问题标题】:BeautifulSoup - How to remove nested tags with no text and blank space from the end of HTMLBeautifulSoup - 如何从 HTML 末尾删除没有文本和空格的嵌套标签
【发布时间】:2015-10-16 02:43:14
【问题描述】:

我正在尝试使用 BeautifulSoup 删除其中没有文本的标签。例如我有以下标签:

<p>
   <p>
       <br/>
   </p>
</p>

<p>
   <br/>
</p>

我有以下功能:

@staticmethod
def stripTagWithNoText(soup,tagname,**kwargs):
    """Strip tags with no text"""
    #Make sure that soup and tags were defined
    assert isinstance(tagname,str)

    #Remove tags with no text
    for tag in soup.find_all(tagname):
        if tag.string:
            continue
        for subtag in tag.findChildren():
            if subtag.string:
                break
        else:
            continue
        tag.extract()

不过,这也会删除如下标签:

<p>This is some random text</p>

谁能看出这有什么问题?

另外,假设我在 html 的末尾附加了以下内容:

<p><br />
</p><p><br /> 
</p><p><br />
</p><p><br /> 
</p><p><br />
</p><p><br />
</p>

有没有办法从类似于 string_text.strip() 的 html 末尾删除所有空格?

注意 我正在使用 Python3、bs4

【问题讨论】:

  • 了解它的 bs3 还是 4...python 2 还是 3 会很有帮助。
  • 我使用的是 Python3、bs4
  • 如果答案对您不起作用,请发布有问题的 html,以便我可以使用真实的测试用例。

标签: python beautifulsoup


【解决方案1】:

这对你有用吗?

from bs4 import BeautifulSoup
from bs4.element import Tag

def main():
    test = """
    <p>
    this should not be here
       <p>this should not be here
           <br/>this should not be here
       </p>
       this should not be here
    </p>
    """
    soup = BeautifulSoup(test, 'html.parser')

    def stripTagWithNoText(soup, tagname):
        def remove(node):
            for index, item in enumerate(node.contents):
                if isinstance(item, Tag):
                    remove(node.contents[index])
                else:
                    node.contents[index] = ''

        #Remove tags with no text
        for tag in soup.find_all(tagname):
            remove(tag)
        print(soup)

    stripTagWithNoText(soup, 'p')
    return 0

if __name__ == '__main__':
    main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-19
    • 1970-01-01
    • 1970-01-01
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多