Introduction to the Wikipedia module in Python

by K. Yue

1. Wikipedia

2. wikipedia module

Example:

wiki_ex3.py

import wikipedia

title = "University of Houston-Clear Lake"
#   Use wikipedage to get the page with the title.
#   Turn off automatic suggestion.
page = wikipedia.page(title, auto_suggest=False)

#   print some selected information from Wikipedia
print(f"Information about Wikipedia page on {title}")
print(f"1. Page Title: {page.title}")
print(f"2. Page URL: {page.url}")
summary = wikipedia.summary(title, sentences=3, auto_suggest=False)
print(f"3. Summary:\n{summary}")
num_images = len(page.images)
print(f"4. Number of Images: {num_images}")

 

Notes:

  1. Two methods/functions of the wikipedia object are called:
    1. page
    2. summary
  2. "page = wikipedia.page(title, auto_suggest=False)" returns an object and set the variable page to refer to it.
  3. f strings are used.

wiki_ex4.py (geosearch)

import wikipedia

page = wikipedia.page("Golden Gate Bridge", auto_suggest=False)
golden_gate_lat = page.coordinates[0]
golden_gate_lon = page.coordinates[1]
print(f"Golden Gate Bridge geocode: [{golden_gate_lat}, {golden_gate_lon }]")

# Perform a geosearch around the Golden Gate Bridge
nearby_golden_gate = wikipedia.geosearch(golden_gate_lat, golden_gate_lon, results=4, radius=3000)
print(nearby_golden_gate)
print(f"Wikipedia pages near the Golden Gate Bridge:")
for page_title in nearby_golden_gate:
    print(f"- {page_title}")

Notes:

  1. page.coordinates contain the (x,y) coordinates of the page.
  2. wikipedia.geosearch searches Wikipedia using the supplied coordinates (arguments #1 and #2). It returns a list of search results.
  3. The for loop is used to iterate through the list nearby_golden_gate.