繁体   English   中英

从HTML标签删除评论

[英]Remove Comments from HTML Tags

关于如何使用BeautifulSoup从HTML剥离注释标签? ,我正在尝试从以下标签中删除评论

>>> 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.7BeautifulSoup4吗? 如果不是后者,我将安装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

注意:发布print声明是一件好事。 否则就不会知道它是Python 2。 发布Python版本也有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM