Home » Get wikipedia information using python

Get wikipedia information using python

by maxguy71

In this article we look at a Python library that makes it easy to access and parse data from Wikipedia.

Installation

To install Wikipedia, simply run:

$ pip install wikipedia

Examples

The first returns a list of all articles that contain the searched query. This method will return the title and the related search.

Basic example

import wikipedia  
# Searching a title  
print(wikipedia.search("Scotland"))

When run you will see something like this

>>> %Run wikipediasearch.py
[‘Scotland’, ‘Scotland Yard’, ‘Scottish Gaelic’, ‘James VI and I’, ‘Patricia Scotland’, ‘List of Scottish monarchs’, ‘William III of England’, ‘Mary, Queen of Scots’, ‘Church of Scotland’, ‘Acts of Union 1707’]

You can also limit the amount of results returned by specifying the results to be returned, in this example 2

import wikipedia  
# Searching a title  
print(wikipedia.search("Scotland"))
print(wikipedia.search("Scotland", results = 2)) 

When run you will see something like this

>>> %Run wikipediasearch.py
[‘Scotland’, ‘Scotland Yard’, ‘Scottish Gaelic’, ‘James VI and I’, ‘Patricia Scotland’, ‘List of Scottish monarchs’, ‘William III of England’, ‘Mary, Queen of Scots’, ‘Acts of Union 1707’, ‘Scottish Highlands’]
[‘Scotland’, ‘Scotland Yard’]

Get a Suggestion

You can try and get a suggestion by using the suggest method, lets take this example

import wikipedia  
  
print(wikipedia.suggest("Scotlund"))  

This displayed the following for me

scotland

Display the summary of a page

You can display t he summary of a page by using the summary method and also restrict the sentences returned using the sentences parameter

import wikipedia  
  
print(wikipedia.summary("Scotland", sentences=3)) 

In my case it returned the following

>>> %Run wikipediasummary.py
Scotland (Scots: Scotland, Scottish Gaelic: Alba [ˈal̪ˠapə] (listen)) is a country that is part of the United Kingdom. Covering the northern third of the island of Great Britain, mainland Scotland has a 96-mile (154-kilometre) border with England to the southeast and is otherwise surrounded by the Atlantic Ocean to the north and west, the North Sea to the northeast and the Irish Sea to the south. The country also contains more than 790 islands, principally in the archipelagos of the Hebrides and the Northern Isles.

Getting Full Page

You can get the full Wikipedia using the page() function. It returns the page content, categories, coordinate, images, links and other metadata.

Links

github link with examples

Read the docs at https://wikipedia.readthedocs.org/en/latest/.

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More