引用How can I strip comment tags from HTML using BeautifulSoup? ,我正在尝试删除以下标签中的评论
>>> h
<h4 class="col-sm-4"><!-- react-text: 124 -->52 Week High/Low:<!-- /react-text --><b><!-- react-text: 126 --> ₹ <!-- /react-text --><!-- react-text: 127 -->394.00<!-- /react-text --><!-- react-text: 128 --> / ₹ <!-- /react-text --><!-- react-text: 129 -->252.10<!-- /react-text --></b></h4>
我的代码 -
comments = h.findAll(text=lambda text:isinstance(text, Comment))
[comment.extract() for comment in comments]
print h
但是搜索评论却一无所获。我想从上述标签中提取 2 个值 - “52 周最高价/最低价:” 和 “卢比 394.00/卢比 252.10”。
我还尝试使用删除整个 html 中的标签
soup = BeautifulSoup(html)
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
[comment.extract() for comment in comments]
print soup
但是评论仍然存在..有什么建议吗?
最佳答案
您使用的是Python2.7
和BeautifulSoup4
吗?如果不是后者,我会安装 BeautifulSoup4
。
pip install beautifulsoup4
以下脚本对我有用。我刚刚复制并粘贴了您上面的问题并运行了它。
from bs4 import BeautifulSoup, Comment
html = """<h4 class="col-sm-4"><!-- react-text: 124 -->52 Week High/Low:<!-- /react-text --><b><!-- react-text: 126 --> ₹ <!-- /react-text --><!-- react-text: 127 -->394.00<!-- /react-text --><!-- react-text: 128 --> / ₹ <!-- /react-text --><!-- react-text: 129 -->252.10<!-- /react-text --></b></h4>"""
soup = BeautifulSoup(html)
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
# nit: It isn't good practice to use a list comprehension only for its
# side-effects. (Wastes space constructing an unused list)
for comment in comments:
comment.extract()
print soup
Note: It's a good thing you posted the
关于html - 删除 HTML 标签中的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38168118/