Search code examples
pythonapiwikipedia

A Random Wikipedia Article Generator


I have this Random Wikipedia Article Generator that I have created but I want that it will generate an article about a specific topic and for some reason, it generates articles but not about the topic that I have entered.

Code:

import requests
from bs4 import BeautifulSoup
import webbrowser

while True:
        topic = input("Plz enter a topic you would like to read about: ")
        url = requests.get(f"https://en.wikipedia.org/wiki/Special:Random/{topic}")
        soup = BeautifulSoup(url.content, "html.parser")
        title = soup.find(class_="firstHeading").text   

        answer = input(f"The article is: {title} \nWould you like to view this article? (Y/N)\n").upper()

        if answer == "Y":
                url = "https://en.wikipedia.org/wiki\%s" %title
                webbrowser.open(url)


                leave = input("Would you like to read another one? (Y/N)\n").upper()
                if leave == "Y":
                        pass
                else:
                        break
        elif answer == "N":
                print("Try again!!")
        else:
                print("I don't know what it is")

Solution

  • According to: https://en.wikipedia.org/wiki/Wikipedia:Special:Random

    The endpoint for a categorized random subject is: https://en.wikipedia.org/wiki/Special:RandomInCategory/

    And not: https://en.wikipedia.org/wiki/Special:Random/

    So you should change your url to:

    url = requests.get(f"https://en.wikipedia.org/wiki/Special:RandomInCategory/{topic}")