首页 > 编程语言 > 详细

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

时间:2015-06-01 01:04:03      阅读:702      评论:0      收藏:0      [点我收藏+]

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

简单HTML源码:

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代码中的注释:

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

输出结果:

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


参考:

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

2、BeautifulSoup documentation #Removing elements








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

原文:http://my.oschina.net/ioslighter/blog/423166

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!