Random Wikipedia Article Generator
Oct 26, 2022
PythonWeb ScrapingScripting

Random Wikipedia Article Generator

This python script 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 true loop encompasing all of it. Then simply the openning of the url based on the user's choice is left to the last if-else part.

1import requests
2from bs4 import BeautifulSoup
3import webbrowser
4
5
6while True:
7    a = "https://en.wikipedia.org/wiki/Special:Random"
8    u = requests.get(a)
9    soup = BeautifulSoup(u.content, 'html.parser')
10    title = soup.find(class_ = "firstHeading").text
11    print(title + "\nDo You want to view it? (Y/N)")
12    ans = str(input(""))
13    if (ans.lower() == "y"):
14        url = 'https://en.wikipedia.org/wiki/%s' %title
15        webbrowser.open(url)
16        break
17    elif (ans.lower() == "n"):
18        print("ok\nTrying again!")
19        continue
20    else:
21        print("Wrong Choice!!!")
22        break

Output:

ss.png

Comment

Related Posts

Categories