傻瓜式文章爬蟲-newspaper庫簡介

今天比較閒,我就瀏覽了會github上有關python爬蟲的項目。看到一個newspaper庫,關注數挺高的。作者受lxml的強大和requests的簡潔,開發了newspaper庫。

requests庫的作者都盛讚newspaper庫的牛B。

"Newspaper is an amazing python library for extracting & curating

 articles." -- tweeted by Kenneth Reitz, Author of requests

一、newspaper特性

  • 多進程文章下載框架

  • 新聞鏈接識別

  • 可從html文件中提取文本、圖片

  • 可文章關鍵詞提取

  • 可生成文章概要

  • 提取文章作者名

  • 谷歌趨勢詞提取

  • 支持十數種語言(含中文)

其實之前我寫過一個類似的庫的介紹-goose(僅支持python2),跟newspaper有類似功能。 文章名《不會寫爬蟲的快來goose一下》

二、安裝


pip3 install newspaper3k

注意:在python3中安裝,必須是newspaper3k。 newspaper是python2上的庫。

三、開始代碼
3.1newspaper支持的語言

import newspaper

print(newspaper.languages())

Your available languages are:

input code        full name

  ar              Arabic

  da              Danish

  de              German

  el              Greek

  en              English

  es              Spanish

  fi              Finnish

  fr              French

  he              Hebrew

  hu              Hungarian

  id              Indonesian

  it              Italian

  ko              Korean

  mk              Macedonian

  nb              Norwegian (Bokmål)

  nl              Dutch

  no              Norwegian

  pt              Portuguese

  ru              Russian

  sv              Swedish

  tr              Turkish

  vi              Vietnamese

  zh              Chinese

3.2 文章內容提取
提取文章內容,如作者、出版日期、文章內容、圖片鏈接


from newspaper import Article

url = 'http://media.china.com.cn/cmyw/2017-06-13/1067887.html'

article = Article(url, language='zh')

#下載文章

article.download()

#查看文章的html數據

#print(article.html)

#解析文章html數據

article.parse()

#提取各種數據信息

#作者

print(article.authors)

#出版日期

print(article.publish_date)

#新聞內容

print(article.text)

#文章的首圖鏈接

print(article.top_image)

3.3 自然語言處理
繼續3.2部分代碼


#nlp初始化

article.nlp()

#提取關鍵詞

print(article.keywords)

#文章概要

print(article.summary)

3.4 更精細的使用方法
上面的方法是默認的方法,如果你確定某網站採用的全部是一種語言,你可以使用下面代碼


#文檔中使用的案例

import newspaper

sina_paper = newspaper.build('http://www.sina.com.cn/', language='zh')

for category in sina_paper.category_urls():

    print(category)

輸出了新浪網所有欄目


http://roll.fashion.sina.com.cn

http://www.sina.com.cn/

http://hainan.sina.com.cn

http://jiangsu.sina.com.cn

http://vr.sina.cn

http://cq.auto.sina.com.cn

http://eladies.sina.com.cn

http://chuangye.sina.com.cn

http://gx.sina.com.cn

http://slide.mil.news.sina.com.cn

http://hlj.sina.com.cn

http://history.sina.com.cn

.

.

.

http://tech.sina.com.cn//nmg.sina.com.cn

http://shiqu.sina.com.cn

http://ah.sina.com.cn

http://slide.news.sina.com.cn

http://chexian.sina.com

總結,用着效果沒有requests作者誇的那麼棒,可能我找的網站正好是newspaper無法完美處理的網站。

Tips:這篇文章抓的是外國網站-Twitter每日推薦導讀

《藉助Python Newspaper庫創建Read It Later App》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章