首页 > 解决方案 > 如何使用 Beautiful Soup 删除 html 评论

问题描述

我正在清除爬网网站中的文本,但我不想在我的数据中添加任何 html 注释,所以我必须自己解析它还是有现有的功能可以这样做?

我试过这样做:

from bs4 import BeautifulSoup as S
soup = S("<!-- t --> <h1>Hejsa</h1> <style>html{color: #0000ff}</style>")
soup.comment # == None
soup.style   # == <style>html{color: #0000ff}</style>

标签: pythonbeautifulsoup

解决方案


要搜索表单 HTML 注释,您可以使用bs4.Commenttype:

from bs4 import BeautifulSoup, Comment

html_doc = '''
    <!-- t --> <h1>Hejsa</h1> <style>html{color: #0000ff}</style>
'''

soup = BeautifulSoup(html_doc, 'html.parser')

# print comment:
comment = soup.find(text=lambda t: isinstance(t, Comment))
print( comment )

印刷:

t

要提取它:

comment = soup.find(text=lambda t: isinstance(t, Comment))

# extract comment:
comment.extract()
print(soup.prettify())

印刷:

<h1>
 Hejsa
</h1>
<style>
 html{color: #0000ff}
</style>

推荐阅读