Python爬虫万金油,使用工具goose快速提取网页内容_python goose(1)

126 阅读3分钟

我找到一个 python 3 的版本 goose3

pip install goose3

经过我一些简单的测试,未发现两个版本在结果上有太大的差异。

快速上手

这里使用 goose3,而 python-goose 只要把其中的 goose3 改成 goose 即可,接口都是一样的。以一篇文章 如何用Python抓抖音上的小姐姐 为抓取目标来做个演示。

from goose3 import Goose
from goose3.text import StopWordsChinese
# 初始化,设置中文分词
g = Goose({'stopwords_class': StopWordsChinese})
# 文章地址
url = 'https://mp.weixin.qq.com/s/zflbcF5PS06QC5YJXpiviQ'
# 获取文章内容
article = g.extract(url=url)
# 标题
print('标题:', article.title)
# 显示正文
print(article.cleaned_text)

输出:

除了标题 title 和正文 cleaned_text 外,还可以获取一些额外的信息,比如:

  • meta_description:摘要
  • meta_keywords:关键词
  • tags:标签
  • top_image:主要图片
  • infos:包含所有信息的 dict
  • raw_html:原始 HTML 文本

如有有些网站限制了程序抓取,也可以根据需要添加user-agent信息:

g = Goose({'browser_user_agent': 'Version/5.1.2 Safari/534.52.7'})

如果是 goose3,因为使用了 requests 库作为请求模块,因此还可以以相似方式配置headers、proxies 等属性。

在上述示例中使用到的 StopWordsChinese 为中文分词器,可一定程度上提高中文文章的识别准确率,但更耗时。

其他说明

Goose 虽然方便,但并不能保证每个网站都能精确获取,因此适合大规模文章的采集,如热点追踪、舆情分析等。它只能从概率上保证大多数网站可以相对准确地抓取。我经过一些尝试后发现,抓取英文网站优于中文网站,主流网站优于小众网站,文本的提取优于图片的提取。

从项目中的requirements.txt 文件可以看出,goose 中使用到了Pillow、lxml、cssselect、jieba、beautifulsoup、nltk,goose3 还用到了 requests。

如果你是使用基于 python2 的 goose,有可能会遇到编码上的问题(尤其是 windows 上)。

除了 goose 外,还有其他的正文提取库可以尝试,比如python-boilerpipe、python-readability 等。

实例

最后,我们来用 goose3 写小一段代码,自动抓取 爱范儿、雷锋网、DoNews上的新闻文章:

from goose3 import Goose
from goose3.text import StopWordsChinese
from bs4 import BeautifulSoup

g = Goose({'stopwords_class': StopWordsChinese})
urls = [    'https://www.ifanr.com/',    'https://www.leiphone.com/',    'http://www.donews.com/']
url_articles = []
for url in urls:
    page = g.extract(url=url)
    soup = BeautifulSoup(page.raw_html, 'lxml')
    links = soup.find_all('a')
    for l in links:
        link = l.get('href')
        if link and link.startswith('http') and any(c.isdigit() for c in link if c) and link not in url_articles:
            url_articles.append(link)
            print(link)

for url in url_articles:
    try:
        article = g.extract(url=url)
        content = article.cleaned_text
        if len(content) > 200:
            title = article.title
            print(title)
            with open('homework/goose/' + title + '.txt', 'w') as f:
                f.write(content)
    except:
        pass

这段程序所做的事情就是:

  1. 抓取网站首页
  2. 从页面上提取地址中带有数字的链接
  3. 抓取这些链接,提取正文。如果结果超过 200 个字,就保存成文件

效果:

img img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!