如何使用Beauty Soup删除html注释

2024-06-28 20:37:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在清理爬网网站上的文本,但我不想在我的数据中包含任何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>

Tags: 数据函数from文本import网站stylehtml
2条回答

要搜索表单HTML注释,可以使用bs4.Comment类型:

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>

使用正则表达式

import re
html = "<!  t  > <h1>Hejsa</h1> <style>html{color: #0000ff}</style>"
html = re.sub('<! [\s\S]* >', '', html).strip()
print(html)

结果:

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

相关问题 更多 >