Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonライブラリ「newspaper3k」でニュース記事をスクレイピング&キュレーションする方法

Webページからコンテンツを抽出する技術は、データマイニングや情報検索など、さまざまな分野で活用されています。本記事では、新聞社や雑誌のWebサイトから情報を抽出できるPythonライブラリ「newspaper(newspaper3k)」の使い方を解説します。

このライブラリの主な目的は、新聞サイトなどを対象に記事を自動的に抽出し、キュレーションすることです。著者名、メイン画像、公開日、埋め込み動画、キーワード、記事の要約といった情報をまとめて取得できるのが特徴です。

インストール方法

まず、ターミナルで以下のコマンドを実行し、newspaperライブラリをインストールします。

$ pip install newspaper3k

続いて、依存関係となるXML解析ライブラリ「lxml」をインストールします。

$ pip install lxml

画像処理に必要なPIL(Pillow)もインストールしておきましょう。

$ pip install Pillow

最後に、キーワード抽出や要約生成に使うNLP(自然言語処理)用のコーパスをダウンロードします。

$ curl https://raw.githubusercontent.com/codelucas/newspaper/master/download_corpora.py | python

基本的な使い方:記事情報の取得

newspaperライブラリを使うと、記事の著者名、公開日、メイン画像のURL、キーワード、要約などの情報を簡単に収集できます。ここでは、ウォール・ストリート・ジャーナル(WSJ)の記事を例に説明します。

# 必要なライブラリをインポート
from newspaper import Article

# 抽出したい記事のURL
url = "https://www.wsj.com/articles/lawmakers-to-resume-stalled-border-security-talks-11549901117"

# 記事をダウンロード
article = Article(url)
article.download()

# 記事を解析して著者名を取得
article.parse()
print(article.authors)

実行結果

['Kristina Peterson', 'Andrew Duehren', 'Natalie Andrews', 'Kristina.Peterson Wsj.Com', 'Andrew.Duehren Wsj.Com', 'Natalie.Andrews Wsj.Com']

同じように、公開日とメイン画像のURLも取得できます。

# 公開日を取得
print("Article Publication Date:")
print(article.publish_date)

# メイン画像のURLを取得
print(article.top_image)

実行結果

https://images.wsj.net/im-51122/social

※ サイトによっては公開日がHTML上に明記されておらず、publish_dateNoneになる場合があります。

NLPによるキーワードと要約の抽出

nlp()メソッドを実行すると、自然言語処理によって記事のキーワードと要約を自動生成できます。

# キーワード抽出(NLP)
article.nlp()
print("Keywords in the article", article.keywords)

# 記事の要約を取得
print("Article Summary", article.summary)

完全なサンプルプログラム

ここまでの処理をまとめた完全なコードが以下です。

from newspaper import Article

url = "https://www.wsj.com/articles/lawmakers-to-resume-stalled-border-security-talks-11549901117"
article = Article(url)
article.download()
article.parse()
print(article.authors)
print("Article Publication Date:")
print(article.publish_date)
print("Major Image in the article:")
print(article.top_image)
article.nlp()
print("Keywords in the article")
print(article.keywords)
print("Article Summary")
print(article.summary)

実行結果

['Kristina Peterson', 'Andrew Duehren', 'Natalie Andrews', 'Kristina.Peterson Wsj.Com', 'Andrew.Duehren Wsj.Com', 'Natalie.Andrews Wsj.Com']
Article Publication Date:
None
Major Image in the article:
https://images.wsj.net/im-51122/social
Keywords in the article
['state', 'spending', 'sweeping', 'southern', 'security', 'border', 'principle', 'lawmakers', 'avoid', 'shutdown', 'reach', 'weekendthe', 'fund', 'trump', 'union', 'agreement', 'wall']
Article Summary
President Trump made the case in his State of the Union address for the construction of a wall along the southern U.S. border, calling it a “moral issue.”
Photo: GettyWASHINGTON—Senior lawmakers said Monday night they had reached an agreement in principle on a sweeping deal to end a monthslong fight over border security and avoid a partial government shutdown this weekend.
The top four lawmakers on the House and Senate Appropriations Committees emerged after three closed-door meetings Monday and announced that they had agreed to a framework for all seven spending bills whose funding expires at 12:01 a.m. Saturday.

このように、newspaper3kを使えば数行のコードで記事のメタ情報から本文の要約まで一括取得できます。ニュースアグリゲーターの構築や、機械学習用のテキストデータ収集など、幅広い用途に活用できる強力なライブラリです。

  1. Pythonのgetpassモジュールとは?パスワード入力とユーザー名取得の基本を解説

    Pythonの標準ライブラリには、ターミナル上で動作するアプリケーションにおいて、ユーザーの認証情報を検証してから処理を実行したい場合に役立つgetpassモジュールが用意されています。このモジュールには主に2つの関数が定義されており、セキュリティを意識したコマンドラインツールの開発に欠かせない存在です。 getpass() 関数:パスワードを安全に入力する getpass()関数は、ユーザーにパスワードの入力を促すための関数です。デフォルトでは、ターミナルに入力されたキーは画面に表示(エコー)されないため、第三者にパスワードを盗み見られる心配がありません。 また、プロンプトとして表示される

  2. PythonでWebスクレイピング!主要ライブラリ6選の特徴と使い方を徹底解説

    Webスクレイピングとは コンピュータサイエンスにおけるWebスクレイピング(Web Scraping)とは、Webサイトからデータを抽出する技術のことです。この手法を活用することで、Web上に散在する非構造化データを、分析や加工がしやすい構造化データへと変換できます。 Python 3でよく使われる代表的なスクレイピングツールは以下の6つです。 Urllib(urllib.request) Requests BeautifulSoup Lxml Selenium MechanicalSoup 1. Urllib(urllib.request) UrllibはPythonに標準で組み込ま