常见的提取网页正文的方法

 Python readability的使用:

 from readability.readability import Document

import urllib

html = urllib.urlopen(url).read()

readable_article = Document(html).summary()

readable_title = Document(html).short_title()

      最后抽取出来的readable_article是带HTML标签的文本。还需要进行clean html操作。如果需要得到纯文本内容,还需要做其他工作。

      例如,提取正文

             response = HtmlResponse(url='', body=readable_article, encoding='utf8')
             hxs = HtmlXPathSelector(response)

             html_content = ''.join(hxs.select('//text()').extract()).strip()

不过这种方式有好多情况提取不到正文。

Python Newspaper的使用:

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

核心示例代码如下所示:

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

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

Python Goose的使用:

代码比较方便,但是有些网址没有解析出来。

 示例代码如下所示:

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]

结果:效果不好,有些网址解析不出来。

转载于:https://www.cnblogs.com/zhaobang/p/7472091.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值