【问题标题】:BeautifulSoup4 extract all types of conditional commentsBeautifulSoup4 提取所有类型的条件注释
【发布时间】:2018-10-23 14:50:11
【问题描述】:

我想做什么:

使用 bs4 从 html 邮件中删除可疑的 cmets。现在我遇到了downlevel-revealed 类型的所谓conditional comments 的问题。

见:https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/compatibility/ms537512(v=vs.85)#syntax-of-conditional-comments

import bs4

html = 'A<!--[if expression]>a<![endif]-->' \
       'B<![if expression]>b<![endif]>'


soup = bs4.BeautifulSoup(html, 'html5lib')

for comment in soup.find_all(text=lambda text: isinstance(text, bs4.Comment)):
    comment.extract()

提取 cmets 之前:

'A',
'[if expression]>a<![endif]',
'B',
'[if expression]',
'b',
'[endif]',

提取cmets后:

'A',
'B',
'b',

问题:

小b也应该去掉。问题是,bs4 将第一个评论检测为单个评论对象,但第二个被检测为 3 个对象。 Comment(if)、NavigableString(b) 和 Comment(endif)。提取只是删除了这两种评论类型。内容为“b”的 NavigableString 仍保留在 DOM 中。

有什么解决办法吗?

【问题讨论】:

    标签: python internet-explorer beautifulsoup conditional-comments html5lib


    【解决方案1】:

    在阅读了有关条件 cmets 一段时间后,我可以理解为什么会这样。

    下层隐藏

    downlevel-hidden 基本上写成普通评论&lt;!-- ... --&gt;。这在现代浏览器中被检测为条件注释块。所以如果我想删除条件 cmets,BeautifulSoup 会完全删除它。

    下层显示

    downlevel-revealed 写成&lt;!...&gt;b&lt;!...&gt;,现代浏览器将这两个标签检测为无效并在 DOM 中忽略它们,因此只有 b 仍然有效。所以 BeautifulSoup 只删除标签,而不是内容

    结论

    BeautifulSoup 像现代浏览器一样处理条件 cmets。这对我的情况来说非常好。

    【讨论】:

      猜你喜欢
      • 2014-06-13
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 2018-01-28
      • 2014-07-20
      • 2012-10-03
      • 2017-01-23
      • 2020-11-04
      相关资源
      最近更新 更多