如何从 HTML LXML 中删除注释

How to remove comments from HTML LXML

如何使用 lxml 删除这样的评论而不丢失值 Apple iPhone 5s(Space 灰色,16 GB)

<h1 class="_3eAQiD" data-reactid="144">
<!-- react-text: 145 -->
Apple iPhone 5s (Space Grey, 16 GB)
<!-- /react-text -->
</h1>

使用正则表达式。

import re    

a = '''<h1 class="_3eAQiD" data-reactid="144">
<!-- react-text: 145 -->
Apple iPhone 5s (Space Grey, 16 GB)
<!-- /react-text -->
</h1>'''    

print re.sub("(<!--.*?-->)", "", a, flags=re.MULTILINE)

结果:

<h1 class="_3eAQiD" data-reactid="144">

Apple iPhone 5s (Space Grey, 16 GB)

</h1>

使用 lxml

import  lxml.etree as et
x = et.fromstring(a, parser=et.HTMLParser(remove_comments=True))
print(et.tostring(x))