【问题标题】:How to find all comments with Beautiful Soup如何使用 Beautiful Soup 查找所有评论
【发布时间】:2016-01-13 08:16:27
【问题描述】:

This question 在四年前被问到,但现在答案对于 BS4 来说已经过时了。

我想用漂亮的汤删除我的 html 文件中的所有 cmets。由于 BS4 使每个 comment as a special type of navigable string,我认为这段代码可以工作:

for comments in soup.find_all('comment'):
     comments.decompose()

那没用....如何找到所有使用 BS4 的 cmets?

【问题讨论】:

  • 我想这个answer 应该还能工作。
  • 我收到“未定义全局名称'comment'”
  • 我知道这是旧的,但是@Joseph,如果你从 bs4 导入评论它应该可以工作
  • 确实...接受的答案是正确的。

标签: python html beautifulsoup comments bs4


【解决方案1】:

您可以将一个函数传递给 find_all() 以帮助它检查字符串是否为 Comment。

例如我有下面的html:

<body>
   <!-- Branding and main navigation -->
   <div class="Branding">The Science &amp; Safety Behind Your Favorite Products</div>
   <div class="l-branding">
      <p>Just a brand</p>
   </div>
   <!-- test comment here -->
   <div class="block_content">
      <a href="https://www.google.com">Google</a>
   </div>
</body>

代码:

from bs4 import BeautifulSoup as BS
from bs4 import Comment
....
soup = BS(html, 'html.parser')
comments = soup.find_all(string=lambda text: isinstance(text, Comment))
for c in comments:
    print(c)
    print("===========")
    c.extract()

输出将是:

Branding and main navigation 
============
test comment here
============

顺便说一句,我认为find_all('Comment') 不起作用的原因是(来自 BeautifulSoup 文档):

为 name 传入一个值,你会告诉 Beautiful Soup 只考虑具有特定名称的标签。 文本字符串将被忽略,名称不匹配的标签也会被忽略。

【讨论】:

  • 很高兴找到您的答案,谢谢!知道如何在不使用 lambda 的情况下编写它吗?
【解决方案2】:

我需要做两件事:

首先,导入 Beautiful Soup 时

from bs4 import BeautifulSoup, Comment

其次,这里是提取cmets的代码

for comments in soup.findAll(text=lambda text:isinstance(text, Comment)):
    comments.extract()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-26
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多