分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 代码编程

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

发布时间:2023-09-06 01:08责任编辑:傅花花关键词:暂无标签

 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 Goose2 from goose.text import StopWordsChinese3 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]

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

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

原文地址:http://www.cnblogs.com/zhaobang/p/7472091.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved