python - 如何使用 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>
解决方案
要搜索表单 HTML 注释,您可以使用bs4.Comment
type:
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>
推荐阅读
- electron - 如何在 Electron 中安全地包含 C++ SDK
- react-native - 在弹出警报中集成倒数计时器 React native
- python - 为什么我收到索引错误异常错误?
- wso2 - WSO2 Identity Server 5.8 - SAML2 Web SSO:浏览器兼容性
- rust - 在 rust doc 注释中显示矩阵
- c# - 如何使用带有 Newtonsoft.Json 的对象从 API 获取所有数据,我在 xamarin c# 中收到错误的数据
- python - 在 python 中评估变量赋值语句时的语法错误
- javascript - Reactjs-我不断收到错误:TypeError:company.map 不是函数
- pine-script - 如何在 pine 脚本中将 timeframe.period 作为整数返回?
- html - 如何从网页深层链接到 Microsoft Teams 通话