fetch wikipedia articl in python

To fetch a Wikipedia article using Python, we can use the Wikipedia API. Here's a basic code example that demonstrates how to fetch and print the content of a Wikipedia article:

main.py
import requests
import json

# Set the API endpoint and parameters
url = "https://en.wikipedia.org/w/api.php"
params = {
    "action": "query",
    "format": "json",
    "prop": "extracts",
    "titles": "Python (programming language)"
}

# Make the API request and get the JSON data
response = requests.get(url=url, params=params)
data = json.loads(response.text)

# Parse the JSON data and print the article content
page_id = next(iter(data["query"]["pages"]))
article = data["query"]["pages"][page_id]["extract"]
print(article)
531 chars
21 lines

In this example, we use the requests library to make an HTTP GET request to the Wikipedia API endpoint with the parameters we want. We then use json.loads() to parse the JSON response data into a Python object that we can work with.

Finally, we extract the article content from the parsed JSON data and print it to the console. Note that we are using the prop=extracts parameter to get the article content in HTML format. We could also use other parameters, such as prop=revisions to get the article content in wiki markup format.

gistlibby LogSnag