Home > Software design >  How to print mid popular summary of random post of certain topic from Wikipedia?
How to print mid popular summary of random post of certain topic from Wikipedia?

Time:12-31

I want to print mid popular summary of random post of certain topic from Wikipedia using Wikipedia API but I am getting completely random topic.

I have tried this:

import requests

def get_wikipedia(topic):
    response = requests.get(f"https://en.wikipedia.org/api/rest_v1/page/summary/{topic}")
    resp = response.json()

    if response.status_code == 200:
        summary = resp['extract']
        image = resp['thumbnail']['source']

        print(summary)
        print(image)
    else:
        print("An error occurred while fetching the summary and image.")

BASE_URL = 'https://en.wikipedia.org/w/api.php'

params = {
    'format': 'json',
    'action': 'query',
    'list': 'random',
    'rnnamespace': 0,
    'rnlimit': 1,
    'rnprop': 'title',
    'rnfilterredir': 'nonredirects',
    'formatversion': 2,
    'utf8': 1,
    'utf8mb4': 1,
    'titles': 'Quantum Mechanics'
}

response = requests.get(BASE_URL, params=params)

title = response.json()['query']['random'][0]['title']

get_wikipedia(title)

And also I want to print Mid popular (the articles with page views less than 10k per month) topic. How to do it?

CodePudding user response:

The best approach is probably using the search API with something like incategory:"Quantum mechanics" (see help) and srsort set to random.

  • Related