DEV Community

Dave Parizek
Dave Parizek

Posted on • Updated on

Using Python and the Wikipedia API to Easily Add Wikipedia Summaries to Your Website

Wikipedia has a MediaWiki Action API that you can access to very easily add useful reference content to your website.

For a use case, I use it to add a summary of each author to "quotes by authors" pages for a quotes website. An example here: Quotes by Albert Einstein has a long wikipedia summary about Einstein. The Wikipedia API returns much shorter summaries (typically a single paragraph) for most wikipages.

I use Django and Python, and there is a Python project at https://github.com/goldsmith/Wikipedia that wraps the MediaWiki API to make things super easy.

Installation is easy as pie(-thon):
$ pip install wikipedia

Then import of course:
>>> import wikipedia

Then try:
>>> print wikipedia.summary("Wikipedia")

To get my author summaries, I search for a specific page in a Django view:
wikipage = wikipedia.page("Albert Einstein")

and can then easily grab particulars from the page object and save them to my Author model:
thisterm = "Albert Einstein"
wikipage = wikipedia.page(thisterm)
print("title = " + wikipage.title)
author.wiki_summary = wikipage.summary
author.wiki_url = wikipage.url
author.wiki_title = wikipage.title
author.wiki_images = wikipage.images
author.save()

Super simple! (-:

Two potential issues to plan for:

  1. You should of course limit how often you call the MediaWiki Action API per their guidelines.
  2. Often you will not get an exact match for a page for your searchterm (e.g. John Smith above) - in that case you can look up the specific wikipage id and reference that way.

A huge thank you to developer Jon Goldsmith for creating that Python wikipedia library and making it so easy!

Top comments (0)