Getting Started with Python's Wikipedia API
介绍
在本文中,我们将使用Wikipedia API从Wikipedia检索数据。 由于越来越多地使用数据分析和机器学习工具,数据抓取迅速增长。 互联网是最大的信息来源,因此了解如何从各种来源获取数据非常重要。 由于Wikipedia是Internet上最大和最受欢迎的信息来源之一,因此这是一个自然的起点。
在本文中,我们将看到如何使用Python的Wikipedia API从Wikipedia网站获取各种信息。
安装
为了从Wikipedia提取数据,我们必须首先安装Python Wikipedia库,该库包装了正式的Wikipedia API。 这可以通过在命令提示符或终端中输入以下命令来完成:
1 | $ pip install wikipedia |
安装完成后,我们可以使用Python中的Wikipedia API从Wikipedia中提取信息。 为了在Python中调用Wikipedia模块的方法,我们需要使用以下命令将其导入。
1 | import wikipedia |
搜索标题和建议
1 2 | import wikipedia print(wikipedia.search("Bill")) |
输出:
1 | ['Bill', 'The Bill', 'Bill Nye', 'Bill Gates', 'Bills, Bills, Bills', 'Heartbeat bill', 'Bill Clinton', 'Buffalo Bill', 'Bill & Ted', 'Kill Bill: Volume 1'] |
如您在输出中看到的,将显示搜索到的标题以及相关的搜索建议。 您可以通过传递
1 2 | import wikipedia print(wikipedia.search("Bill", results=2)) |
输出:
1 | ['Bill', 'The Bill'] |
上面的代码仅打印查询的2个搜索结果,因为这是我们要求返回的数量。
假设我们需要获取错误输入或有错字的搜索标题" Bill Cliton"的Wikipedia搜索建议。
让我们在这里尝试一下:
1 2 | import wikipedia print(wikipedia.suggest("Bill cliton")) |
输出:
1 | bill clinton |
您会看到我们输入了错误的" Bill clinton",并返回了正确的建议" bill clinton"。
提取维基百科文章摘要
我们可以使用
让我们提取" Ubuntu"的摘要:
1 | print(wikipedia.summary("Ubuntu")) |
输出:
1 | 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". |
整个摘要将打印在输出中。 通过配置方法的
1 | print(wikipedia.summary("Ubuntu", sentences=2)) |
输出:
1 | 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的文本摘要仅打印了两个句子。
但是,请记住,如果页面不存在或页面是明确的,则
1 | print(wikipedia.summary("key")) |
上面的代码抛出
输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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) ... |
例如,如果您想要摘要关于"加密密钥",则必须输入以下内容:
1 | print(wikipedia.summary("Key (cryptography)")) |
通过更具体的查询,我们现在在输出中获得正确的摘要。
检索完整的维基百科页面数据
为了获取Wikipedia页面的内容,类别,坐标,图像,链接和其他元数据,我们必须首先获取Wikipedia页面对象或页面的页面ID。 为此,将
看下面的例子:
1 | wikipedia.page("Ubuntu") |
此方法调用将返回一个
提取页面的元数据
要获得Wikipedia页面的完整纯文本内容(不包括图像,表格等),我们可以使用
1 | print(wikipedia.page("Python").content) |
输出:
1 2 | 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. ... |
同样,我们可以使用
1 | print(wikipedia.page("Python").url) |
输出:
1 | https://en.wikipedia.org/wiki/Python_(programming_language) |
通过使用
1 | print(wikipedia.page("Python").references) |
输出:
1 | [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', ...] |
1 | print(wikipedia.page("Python").title) |
输出:
1 | Python (programming language) |
类似地,
1 | print(wikipedia.page("Python").categories) |
输出量
1 | ['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'] |
1 | print(wikipedia.page("Ubuntu").links) |
输出量
1 | [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', ...] |
根据坐标查找页面
1 | print(wikipedia.geosearch(37.787, -122.4)) |
输出:
1 | ['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'] |
如您所见,以上方法根据提供的坐标返回文章。
同样,我们可以设置
1 | print(wikipedia.page(37.787, -122.4)) |
输出:
1 | ['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'] |
语言设定
您可以将Wikipedia页面的语言自定义为您的母语,前提是该页面以您的母语存在。 为此,可以使用
1 2 | wikipedia.set_lang("de") print(wikipedia.summary("ubuntu", sentences=2)) |
输出量
1 | 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语言列表及其前缀,如下所示:
1 | print(wikipedia.languages()) |
检索维基百科页面中的图像
1 | print(wikipedia.page("ubuntu").images[0]) |
输出量
1 | https://upload.wikimedia.org/wikipedia/commons/1/1d/Bildschirmfoto_zu_ubuntu_704.png |
上面的代码返回Wikipedia页面中索引0处存在的图像的URL。
要查看图像,您可以将以上URL复制并粘贴到浏览器中。
检索完整的HTML页面内容
要获取HTML格式的完整Wikipedia页面,可以使用以下脚本:
1 | print(wikipedia.page("Ubuntu").html()) |
输出量
1 2 3 | <div class="mw-parser-output"><div role="note" class="hatnote navigation-not-searchable">For the African philosophy, see <a href="/wiki/Ubuntu_philosophy" title="Ubuntu philosophy">Ubuntu philosophy</a>. For other uses, see <a href="/wiki/Ubuntu_(disambiguation)" class="mw-disambig" title="Ubuntu (disambiguation)">Ubuntu (disambiguation)</a>.</div> <div class="shortdescription nomobile noexcerpt noprint searchaux" style="display:none">Linux distribution based on Debian</div> ... |
从输出中可以看到,将以HTML格式显示整个页面。 如果页面很大,则加载时间可能会更长一些,因此请记住,当对服务器的请求超时时,它可能会引发
结论
在本教程中,我们瞥见了使用Wikipedia API从网络提取数据的过程。 我们看到了如何获取各种信息,例如页面的标题,类别,链接,图像,以及如何根据地理位置检索文章。