0

我尝试做的事情:

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

请参阅: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()

提取评论之前:

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

提取评论后:

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

问题:

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

有什么解决办法吗?

4

1 回答 1

0

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

下层隐藏

downlevel-hidden基本上都写成正常的评论<!-- ... -->。这在现代浏览器中被检测为条件注释块。所以如果我想删除条件评论,BeautifulSoup 会完全删除它。

下层显示

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

结论

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

于 2018-11-14T11:31:59.057 回答