Python Show-Me-the-Code 第 0008 题 提取HTML正文内容
2015-05-07 10:28
513 查看
第 0008 题:一个HTML文件,找出里面的正文。
思路:我把这里的正文理解为网页中我主要内容,那么怎么去抓取这个主要内容呢?我一开始的想法是用beautifulsoup来解析网页,但是又想到如果要抽取正文的话这样做还涉及到比较复杂的算法,而且对于不同的网页来说效果可能做不到很好。后来我发现了Python-goose(Github)这个神器,它是基于NLTK和Beautiful Soup的,分别是文本处理和HTML解析的领导者,目标是给定任意资讯文章或者任意文章类的网页,不仅提取出文章的主体,同时提取出所有元信息以及图片等信息,支持中文网页(用到了结巴分词)。这个正好符合需求,所以直接拿来用了。
安装python goose:
git clone https://github.com/grangier/python-goose.git
cd python-goose
pip install -r requirements.txt
python setup.py install
0008.提取HTML正文内容.py
拿阮一峰博客上一篇文章测试,效果如下:
思路:我把这里的正文理解为网页中我主要内容,那么怎么去抓取这个主要内容呢?我一开始的想法是用beautifulsoup来解析网页,但是又想到如果要抽取正文的话这样做还涉及到比较复杂的算法,而且对于不同的网页来说效果可能做不到很好。后来我发现了Python-goose(Github)这个神器,它是基于NLTK和Beautiful Soup的,分别是文本处理和HTML解析的领导者,目标是给定任意资讯文章或者任意文章类的网页,不仅提取出文章的主体,同时提取出所有元信息以及图片等信息,支持中文网页(用到了结巴分词)。这个正好符合需求,所以直接拿来用了。
安装python goose:
git clone https://github.com/grangier/python-goose.git
cd python-goose
pip install -r requirements.txt
python setup.py install
0008.提取HTML正文内容.py
#!/usr/bin/env python #coding: utf-8 from goose import Goose from goose.text import StopWordsChinese import sys reload(sys) sys.setdefaultencoding("utf-8") # 要分析的网页url url = 'http://www.ruanyifeng.com/blog/2015/05/thunk.html' def extract(url): ''' 提取网页正文 ''' g = Goose({'stopwords_class': StopWordsChinese}) article = g.extract(url=url) return article.cleaned_text if __name__ == '__main__': print extract(url)
拿阮一峰博客上一篇文章测试,效果如下:
相关文章推荐
- Python Show-Me-the-Code 第 0009 题 提取网页中的超链接
- Show me the code之Python练习册 Q8~9 html解析
- Python Show-Me-the-Code 第 0017,0018,0019 题 写XML文件
- python show-me-the-code 第0012题
- Python Show-Me-the-Code 第 0012 题 替换敏感词
- 以Python的项目show-me-the-code为例,说明本地git与github
- Python Show-Me-the-Code 第 0023 题 Web留言簿应用
- Show me the code之Python练习册Q23-留言板
- Python Show-Me-the-Code 第 0005 题 批量图片处理
- Python Show-Me-the-Code 第 0000 题 图片右上角加数字
- python 操作 redis --show me the code 0003
- Python Show-Me-the-Code 第 0004 题 统计单词
- python 之 Counter ---show me the code 0004
- python之 heapq -- show me the code 0006
- Python Show-Me-the-Code 第 0022 题 批量图片处理2
- show me the code --python25道练习题
- python PIL --show me the code 0000
- Show me the code之Python练习册 Q10 生成验证码
- Python Show-Me-the-Code 第 0007 题 统计代码行数(注释,空行,总行数)小程序
- python之os -- show me the code 0005