-1

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?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Shounak Das
  • 350
  • 12
  • I am getting completely random post from wikipedia instead of random post from specific category. I have also tried to use `"cmtitle": "Category:Physics"` in other parameter and used `pages = response["query"]["categorymembers"] page = random.choice(pages)` to do it but I am not getting my desirable output – Shounak Das Dec 28 '22 at 19:35
  • 1
    Why did you think that would work? You are asking the API for a random title. [The only thing it supports](https://en.wikipedia.org/w/api.php?action=help&modules=query%2Brandom) is filtering by namespace. – Tgr Dec 29 '22 at 22:23
  • `random.choice(response["query"]["categorymembers"])` should work somewhat, but you are probably only getting some small (deterministic) subset of all category members in a single response, so you'll only draw from those. – Tgr Dec 29 '22 at 22:24
  • 1
    You could try using https://en.wikipedia.org/wiki/Special:RandomInCategory/Quantum_mechanics although it's not really an API (and not quite random in the sense of having a uniform distribution, although for most use cases it should be fine). – Tgr Dec 29 '22 at 22:29

1 Answers1

1

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

Tgr
  • 27,442
  • 12
  • 81
  • 118