提取网页正文的开源库的比较

前段时间在工作中,需要提取出网页的正文,就试验了一下机中提取网页正文开源库。

试验中主要试验了java和python两种提取正文的开源库,测试的连接是:http://www.chinanews.com/gj/2014/11-19/6791729.shtml。结果如下:

 

A.Java:

1.Cx-extractor( http://cx-extractor.googlecode.com):基于行块的分布来提取网页中的正文。

提取的方法是首先使用Jsoup来获取网页的内容,之后将内容传给cx-extractor,交由其来解析,核心代码如下所示:

1 // 通过Jsoup来获取html,在此设置了范文数据包的头部,因为有些网站会屏蔽爬虫。
2 String content = Jsoup.connect("http://www.chinanews.com/gj/2014/11-19/6791729.shtml").userAgent("Mozilla/5.0 (jsoup)").get().html();               
3 // html_article即为解析出的正文。
4 String html_article = CXTextExtract.parse(content);

结果:这个库有时候会有错误,会将不属于正文的内容提取出来,例如一些无关的底部内容,或者一些链接。但性能比较高,约几十毫秒。

2.Boilerpipe(http://code.google.com/p/boilerpipe/):

基于网页dom树来解析,内部有多种解析器,比较准确,但是时间在100毫秒左右。

核心代码如下所示:

1 String content = Jsoup.connect("http://www.chinanews.com/gj/2014/11-19/6791729.shtml").userAgent("Mozilla/5.0 (jsoup)").get().html();
2 // 使用Bolierpipe来获取网页正文内容
3 String parse_article = ArticleExtractor.INSTANCE.getText(content);

 结果:结果比较准确,性能比稍慢,大约在100毫米左右。

B.python

1. Newspaper: 这个库可以实现由网上下载到解析,一条龙服务:

核心示例代码如下所示:

1 from newspaper import Article
2 a = Article('http://www.chinanews.com/gj/2014/11-19/6791729.shtml, language='zh')
3 a.download()
4 a.parse()

结果:耗时会比较长,第一次执行耗时4s左右,解析效果也一般。

2.Python-Goose

代码比较方便,但是,''http://www.chinanews.com/gj/2014/11-19/6791729.shtml,此网址没有解析出来。

 示例代码如下所示:

1 from goose import Goose
2 from goose.text import StopWordsChinese
3 url = 'http://www.chinanews.com/gj/2014/11-19/6791729.shtml'
4 g = Goose({'stipwords_class':StopWordsChinese})
5 article = g.extract(url = url)
6 print article.cleaned_text[:150]

结果:效果不好,解析不出来。

3.Python-readability

示例代码如下所示:

1 from readability.readability import Document
2 import urllib
3 html = urllib.urlopen('http://www.chinanews.com/gj/2014/11-19/6791729.shtml').read()
4 readable_article = Document(html).summary()
5 readable_title = Document(html).short_title()

结果:能过滤出部分正文,但是正文包含很多标签。效果不很好。

最终结合上面结果和项目,选择了“Boilerpipe”,但是仍有部分网页是提取不出来正文的,还需要努力,同时,有些网页不堪忍睹。

原文地址:https://www.cnblogs.com/yetuweiba/p/4149683.html