Skip to content

Instantly share code, notes, and snippets.

@macloo
Last active March 1, 2022 23:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macloo/736e7111c89d14090e76e31411a67fe3 to your computer and use it in GitHub Desktop.
Save macloo/736e7111c89d14090e76e31411a67fe3 to your computer and use it in GitHub Desktop.
Demonstrates extraction of JSON data from a Wikipedia API request - does NOT use the Python library wikipedia-api
"""Demonstrates extraction of data from a Wikipedia API request"""
import requests
API_URL = 'https://en.wikipedia.org/w/api.php?action=query&origin=*&format=json&generator=search&gsrnamespace=0&gsrlimit=10&gsrsearch={}'
search_term = "David_Bowie"
data = requests.get(API_URL.format(search_term)).json()
# put the pages from the result JSON into a list
dict = data["query"]["pages"]
for v in dict.values():
print(v["pageid"])
print(v["title"])
@macloo
Copy link
Author

macloo commented Mar 1, 2022

The Python library for the Wikipedia API - https://wikipedia-api.readthedocs.io/en/latest/README.html

@macloo
Copy link
Author

macloo commented Mar 1, 2022

If you are unfamiliar with Python string formatters (see line 9 in the gist here), this is a good introduction to them:

https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3

@macloo
Copy link
Author

macloo commented Mar 1, 2022

There is (also, alternatively) a more compact way to write string formatters:

https://realpython.com/python-f-strings/#simple-syntax

In my opinion, that would not work as well here — but in other cases, I do prefer the compact style.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment