Random Wikipedia Article Generator in Python

Hello Internet Programmer, Today we build a Random Wikipedia article generator in python.

For this script, we gonna use this https://en.wikipedia.org/wiki/Special:Random to generate articles from Wikipedia. This link generates a random article every time it is clicked.

We use 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.


pip3 install beautifulsoup4

Beautiful Soup is a library that makes it easy to scrape information from web pages. It sits atop an HTML or XML parser, providing Pythonic idioms for iterating, searching, and modifying the parse tree.

pip3 install requests

Requests allows you to send HTTP/1.1 requests extremely easily. There’s no need to manually add query strings to your URLs, or to form-encode your PUT & POST data — but nowadays, just use the json method!

We are also use webbrowser python module but don’t need to install it. It is part of the python standard library.

Now let’s code


import requests
from bs4 import BeautifulSoup
import webbrowser

while True:
    url = requests.get("https://en.wikipedia.org/wiki/Special:Random")
    soup = BeautifulSoup(url.content, "html.parser")
    title = soup.find(class_="firstHeading").text

    print(f"{title} \nDo you want to view it? (Y/N)")
    ans = input("").lower()

    if ans == "y":
        url = "https://en.wikipedia.org/wiki/%s" % title
    elif ans == "n":
        print("Try again!")
        print("Wrong choice!")

So after parsing this https://en.wikipedia.org/wiki/Special:Random link, the same link cannot be used twice for opening after getting the user’s choice, so the link had to be stored before showing the title.

Here we use a while true loop encompassing all of it. Then simply the opening of the URL based on the user’s choice is left to the last if-else part.


random wikipedia article generator in python

When user click Y then Wikipedia site will open with selected title on browser.

image 1

So, This is the random wikipedia article generator using python. Now try this code and share it with your friends. Happy Coding 🙂

Other python stuff,

1 thought on “Random Wikipedia Article Generator in Python”

Leave a Comment

Copy link
Powered by Social Snap