用Python提取HTML源码中的注释与去掉注释

遇到一个编程问题,你必须首先想到的是要简化它,简化成一个最简单的问题后,写最简单的代码来解决它,同时只付出最简单的测试代价。html

简单HTML源码:python

1<!--The loneliest number-->
                        <a>2<!--Can be as bad as one--><b>3


提取上述代码中的注释:编程

from bs4 import BeautifulSoup, Comment

soup = BeautifulSoup("""1<!--The loneliest number-->
                        <a>2<!--Can be as bad as one--><b>3""")
comments = soup.findAll(text=lambda text:isinstance(text, Comment))

for comment in comments:
    print comment

输出结果:测试

The loneliest number
Can be as bad as one

去掉上面HTML代码中的注释:code

from bs4 import BeautifulSoup, Comment

soup = BeautifulSoup("""1<!--The loneliest number-->
                        <a>2<!--Can be as bad as one--><b>3""")
comments = soup.findAll(text=lambda text:isinstance(text, Comment))
[comment.extract() for comment in comments]
print soup

输出结果:htm

1
<a>2<b>3</b></a>


参考:element

一、How to find the comment tag <!--…--> with BeautifulSoup?get

二、BeautifulSoup documentation #Removing elements源码

相关文章
相关标签/搜索