Random Wikipedia Article Generator
Oct 26, 2022
PythonWeb ScrapingScripting

Random Wikipedia Article Generator

This python acript uses Beautiful Soup to generate a random Wikipedia article and then if the user likes that article will open it in the web browser. Otherwise the program will continue to run and generate random articles. For this program I used this to generate a random article from wikipedia. This link generates a random article everytime it is clicked. So after parsing this link the same link cannot be used twice for openning after getting the user's choice, so the link had to be stored before showing the title. So I had to use a while trueloop encompasing all of it. Then simply the openning of the url based on the user's choice is left to the last if-elsepart

import requests
from bs4 import BeautifulSoup
import webbrowser


while True:
    a = "https://en.wikipedia.org/wiki/Special:Random"
    u = requests.get(a)
    soup = BeautifulSoup(u.content, 'html.parser')
    title = soup.find(class_ = "firstHeading").text
    print(title + "\nDo You want to view it? (Y/N)")
    ans = str(input(""))
    if (ans.lower() == "y"):
        url = 'https://en.wikipedia.org/wiki/%s' %title
        webbrowser.open(url)
        break
    elif (ans.lower() == "n"):
        print("ok\nTrying again!")
        continue
    else:
        print("Wrong Choice!!!")
        break

ss.png

Comment

Related Posts

Categories