【发布时间】:2018-10-23 14:50:11
【问题描述】:
我想做什么:
使用 bs4 从 html 邮件中删除可疑的 cmets。现在我遇到了downlevel-revealed 类型的所谓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