PythonのWikipedia APIをはじめよう

この記事では、Wikipedia API を使って Wikipedia からデータを取得することにします。データ分析や機械学習ツールの利用が増加したため、データスクレイピングが急速に普及しています。インターネットは最大の情報源であり、様々なソースからデータを取得する方法を知っておくことは重要です。Wikipediaはインターネット上で最大かつ最も人気のある情報源の1つであり、ここから始めるのは自然なことでしょう。

この記事では、PythonのWikipedia APIを使って、Wikipediaのウェブサイトから様々な情報を取得する方法を紹介します。

インストール

Wikipediaからデータを抽出するためには、まず公式のWikipedia APIをラップしたPython Wikipediaライブラリをインストールする必要があります。これはコマンドプロンプトまたはターミナルで以下のコマンドを入力することで行えます。

$ pip install wikipedia


インストールが完了したら、PythonでWikipedia APIを使用してWikipediaから情報を抽出することができます。PythonでWikipediaモジュールのメソッドを呼び出すには、以下のコマンドを使用してインポートする必要があります。

import wikipedia


タイトルとサジェスチョンを検索する

search()` メソッドは、引数として与えられたクエリに対して Wikipedia の検索を行います。その結果、このメソッドはクエリを含むすべての記事のタイトルのリストを返します。例えば

import wikipedia
print(wikipedia.search("Bill"))


出力されます。

['Bill', 'The Bill', 'Bill Nye', 'Bill Gates', 'Bills, Bills, Bills', 'Heartbeat bill', 'Bill Clinton', 'Buffalo Bill', 'Bill & Ted', 'Kill Bill: Volume 1']


出力にあるように、検索されたタイトルと、関連する検索候補が表示されます。このように、resultsパラメータに値を渡すことで、返される検索タイトルの数を設定することができます。

import wikipedia
print(wikipedia.search("Bill", results=2))


出力されます。

['Bill', 'The Bill']


上記のコードでは、クエリの検索結果が2つだけ表示されます。

例えば、”Bill Cliton “という検索タイトルが誤って入力されていたり、タイプミスがあった場合に、Wikipediaの検索候補を取得する必要があるとしましょう。suggest()` メソッドは、パラメータとして入力された検索クエリに関連する候補を返します。また、候補が見つからなかった場合は “None” を返します。

ここで試してみましょう。

import wikipedia
print(wikipedia.suggest("Bill cliton"))


出力してみましょう。

bill clinton


ビル・クリントン “という間違ったエントリーを選び、”ビル・クリントン “という正しいサジェストを返しているのがわかります。

Wikipediaの記事の要約を抽出する

Wikipedia の記事の要約を抽出するには、summary() メソッドを使います。要約を抽出する必要がある記事は、このメソッドにパラメータとして渡されます。

Ubuntu “の要約を抽出してみましょう。

print(wikipedia.summary("Ubuntu"))


出力します。

Ubuntu ( (listen)) is a free and open-source Linux distribution based on Debian. Ubuntu is officially released in three editions: Desktop, Server, and Core (for the internet of things devices and robots). Ubuntu is a popular operating system for cloud computing, with support for OpenStack.Ubuntu is released every six months, with long-term support (LTS) releases every two years. The latest release is 19.04 ("Disco Dingo"), and the most recent long-term support release is 18.04 LTS ("Bionic Beaver"), which is supported until 2028. Ubuntu is developed by Canonical and the community under a meritocratic governance model. Canonical provides security updates and support for each Ubuntu release, starting from the release date and until the release reaches its designated end-of-life (EOL) date. Canonical generates revenue through the sale of premium services related to Ubuntu. Ubuntu is named after the African philosophy of Ubuntu, which Canonical translates as "humanity to others" or "I am what I am because of who we all are".


出力には要約全体が表示されます。メソッドの引数 sentences を設定することで、表示される要約文の文数をカスタマイズすることができる。

print(wikipedia.summary("Ubuntu", sentences=2))


出力されます。

Ubuntu ( (listen)) is a free and open-source Linux distribution based on Debian. Ubuntu is officially released in three editions: Desktop, Server, and Core (for the internet of things devices and robots).


ご覧の通り、Ubuntuのテキストサマリーは2センテンスしか出力されません。

ただし、wikipedia.summaryでは、ページが存在しない場合やページが曖昧である場合に「曖昧さ解消エラー」を発生させることに注意してください。例を見てみましょう。

print(wikipedia.summary("key"))


上記のコードでは、”key “にマッチする記事がたくさんあるため、DisambiguationErrorを投げています。

出力は

Traceback (most recent call last):
  File "<stdin", line 1, in <module
  File "/Library/Python/2.7/site-packages/wikipedia/util.py", line 28, in __call__
    ret = self._cache[key] = self.fn(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/wikipedia/wikipedia.py", line 231, in summary
    page_info = page(title, auto_suggest=auto_suggest, redirect=redirect)
  File "/Library/Python/2.7/site-packages/wikipedia/wikipedia.py", line 276, in page
    return WikipediaPage(title, redirect=redirect, preload=preload)
  File "/Library/Python/2.7/site-packages/wikipedia/wikipedia.py", line 299, in __init__
    self.__load(redirect=redirect, preload=preload)
  File "/Library/Python/2.7/site-packages/wikipedia/wikipedia.py", line 393, in __load
    raise DisambiguationError(getattr(self, 'title', page['title']), may_refer_to)
wikipedia.exceptions.DisambiguationError: "Key" may refer to: 
Key (cryptography)
Key (lock)
Key (map)
...


例えば、”cryptography key “についての要約が欲しかったとしたら、次のように入力しなければならない。

print(wikipedia.summary("Key (cryptography)"))


より具体的なクエリで、正しい要約が出力されるようになった。

Wikipediaの全ページのデータを取得する

ウィキペディアのページの内容、カテゴリ、座標、画像、リンク、その他のメタデータを取得するためには、まずウィキペディアのページオブジェクト、またはそのページのページ ID を取得する必要があります。これを行うには、 page() メソッドを使用し、その引数として page というタイトルを渡します。

次の例を見てください。

wikipedia.page("Ubuntu")


このメソッド呼び出しは WikipediaPage オブジェクトを返しますが、次のいくつかのセクションで詳しく説明します。

ページのメタデータを抽出する

ウィキペディアのページの完全なテキストコンテンツ (画像やテーブルなどを除く) を取得するには、 page オブジェクトの content 属性を使用することができます。

print(wikipedia.page("Python").content)


出力されます。

Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python's design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and object-oriented approach aims to help programmers write clear, logical code for small and large-scale projects.Python is dynamically typed and garbage-collected. It supports multiple programming paradigms, including procedural, object-oriented, and  functional programming. Python is often described as a "batteries included" language due to its comprehensive standard library.Python was conceived in the late 1980s as a successor to the ABC language. Python 2.0, released 2000, introduced features like list comprehensions and a garbage collection system capable of collecting reference cycles.
...


同様に、 url 属性を使って、そのページの URL を取得することができます。

print(wikipedia.page("Python").url)


出力

https://en.wikipedia.org/wiki/Python_(programming_language)


WikipediaPageオブジェクトのreferences` プロパティを使うと、Wikipedia のページにある外部リンクの URL を取得することができます。

print(wikipedia.page("Python").references)


出力

[u'http://www.computerworld.com.au/index.php/id;66665771', u'http://neopythonic.blogspot.be/2009/04/tail-recursion-elimination.html', u'http://www.amk.ca/python/writing/gvr-interview', u'http://cdsweb.cern.ch/journal/CERNBulletin/2006/31/News%20Articles/974627?ln=en', u'http://www.2ality.com/2013/02/javascript-influences.html', ...]


WikipediaPageオブジェクトのtitle` プロパティを使うと、ページのタイトルを抽出することができます。

print(wikipedia.page("Python").title)


出力

Python (programming language)


同様に、 categories 属性は Wikipedia ページのカテゴリのリストを取得するために使うことができます。

print(wikipedia.page("Python").categories)


出力

['All articles containing potentially dated statements', 'Articles containing potentially dated statements from August 2016', 'Articles containing potentially dated statements from December 2018', 'Articles containing potentially dated statements from March 2018', 'Articles with Curlie links', 'Articles with short description', 'Class-based programming languages', 'Computational notebook', 'Computer science in the Netherlands', 'Cross-platform free software', 'Cross-platform software', 'Dutch inventions', 'Dynamically typed programming languages', 'Educational programming languages', 'Good articles', 'High-level programming languages', 'Information technology in the Netherlands', 'Object-oriented programming languages', 'Programming languages', 'Programming languages created in 1991', 'Python (programming language)', 'Scripting languages', 'Text-oriented programming languages', 'Use dmy dates from August 2015', 'Wikipedia articles with BNF identifiers', 'Wikipedia articles with GND identifiers', 'Wikipedia articles with LCCN identifiers', 'Wikipedia articles with SUDOC identifiers']


WikipediaPageオブジェクトのlinks` 要素は、そのページにリンクされているページのタイトルのリストを取得するために使うことができます。

print(wikipedia.page("Ubuntu").links)


出力

出力“`
[u’/e/ (operating system)’, u’32-bit’, u’4MLinux’, u’ALT Linux’, u’AMD64′, u’AOL’, u’APT (Debian)’, u’ARM64′, u’ARM architecture’, u’ARM v7′, …]




### 座標に基づくページの検索

geosearch()` メソッドは、緯度と経度を float または 10 進数でメソッドに供給して、Wikipedia のジオ検索を行うために使用されます。

print(wikipedia.geosearch(37.787, -122.4))


出力されます。

[‘140 New Montgomery’, ‘New Montgomery Street’, ‘Cartoon Art Museum’, ‘San Francisco Bay Area Planning and Urban Research Association’, ‘Academy of Art University’, ‘The Montgomery (San Francisco)’, ‘California Historical Society’, ‘Palace Hotel Residential Tower’, ‘St. Regis Museum Tower’, ‘Museum of the African Diaspora’]


見ての通り、上記のメソッドは提供された座標に基づいて記事を返します。

同様に、`page()`の座標プロパティを設定し、ジオロケーションに関連する記事を取得することができます。例えば

print(wikipedia.page(37.787, -122.4))


出力されます。

[‘140 New Montgomery’, ‘New Montgomery Street’, ‘Cartoon Art Museum’, ‘San Francisco Bay Area Planning and Urban Research Association’, ‘Academy of Art University’, ‘The Montgomery (San Francisco)’, ‘California Historical Society’, ‘Palace Hotel Residential Tower’, ‘St. Regis Museum Tower’, ‘Museum of the African Diaspora’]




### 言語設定

ウィキペディアのページがあなたの母国語で存在する場合、そのページの言語をあなたの母国語にカスタマイズすることができます。これを行うには、 `set_lang()` メソッドを使用します。各言語は標準的なプレフィックスコードを持っており、このコードはメソッドの引数として渡されます。例えば、"Ubuntu" wikiページの要約文の最初の2文をドイツ語で取得してみましょう。

wikipedia.set_lang(“de”)
print(wikipedia.summary(“ubuntu”, sentences=2))


出力

Ubuntu (auch Ubuntu Linux) ist eine Linux-Distribution, die auf Debian basiert. Der Name Ubuntu bedeutet auf Zulu etwa „Menschlichkeit“ und bezeichnet eine afrikanische Philosophie.


現在サポートされているISO言語のリストとその接頭辞は、以下のように確認できます。

print(wikipedia.languages())




### Wikipediaのページ内の画像を取得する

WikipediaPage` オブジェクトの `images` リストを使用すると、Wikipedia ページから画像を取得することができます。例えば、以下のスクリプトは Wikipedia の Ubuntu ページから最初の画像を返します。

print(wikipedia.page(“ubuntu”).images[0])


出力

https://upload.wikimedia.org/wikipedia/commons/1/1d/Bildschirmfoto_zu_ubuntu_704.png


上記のコードは、Wikipediaページのインデックス0に存在する画像のURLを返しています。

この画像を見るには、上記のURLをコピーして、ブラウザに貼り付けてください。



### HTMLページの全内容を取得する

Wikipediaの全ページをHTML形式で取得するには、以下のスクリプトを使用します。

print(wikipedia.page(“Ubuntu”).html())


出力

“`

出力に見られるように、HTML 形式のページ全体が表示されます。ページサイズが大きい場合、読み込みに少し時間がかかることがあります。そのため、サーバへのリクエストがタイムアウトしたときに `HTMLTimeoutError` が発生する可能性があることを覚えておいてください。

### 結論

In this tutorial, we had a glimpse of using the Wikipedia API for extracting data from the web. We saw how to get a variety of information such as a page’s title, category, links, images, and retrieve articles based on geo-locations.

タイトルとURLをコピーしました