【问题标题】:Remove Comments from HTML Tags从 HTML 标签中删除注释
【发布时间】:2016-11-05 04:56:50
【问题描述】:

参考How can I strip comment tags from HTML using BeautifulSoup?,我正在尝试从下面的标签中删除 cmets

>>> 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

但是搜索 cmets 没有任何结果。我想从上面的标签中提取 2 个值 - "52 Week High/Low:""₹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

但是 cmets 仍然存在.. 有什么建议吗?

【问题讨论】:

    标签: html python-2.7 tags beautifulsoup bs4


    【解决方案1】:

    您使用的是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 版本也有帮助。

    【讨论】:

    • 快速问 - 我不能在这里直接使用标签 - cmets = h.findAll(text=lambda text:isinstance(text, Comment)) 吗? h 是一个标签,并定义了一个 findAll 方法。所以理想情况下它应该工作..但我仍然得到空的 cmets 对象。我们是否需要将 Tag 显式转换回 html 和汤?
    • 当我按原样使用您的代码时它可以工作。但是当我对循环中的每个标签应用评论搜索时,(h中的每个标签)..它失败了..这很奇怪..
    • 让它在完整的 HTML 级别上工作。标签仍然给我空 cmets 数组:-(
    猜你喜欢
    • 2014-11-16
    • 1970-01-01
    • 2020-10-10
    • 2012-04-04
    • 1970-01-01
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    相关资源
    最近更新 更多