Signup/Sign In

Python Project for Random Wikipedia Article

Python Project for Random Wikipedia Article

To produce articles from Wikipedia, we'll use this script: https://en.wikipedia.org/wiki/Special:Random. Every time this link is clicked, a random article is generated.

How to Make a Random Wikipedia Article

We utilize Beautiful Soup to produce a random Wikipedia article, which we then load in the user's web browser if they like it. Otherwise, the application will keep running and producing random articles.

pip3 install beautifulsoup4

Beautiful Soup is a package that makes scraping data from web pages simple. It sits on top of an HTML or XML parser, allowing you to iterate, search, and edit the parse tree using Pythonic idioms.

pip3 install requests

Queries make it very simple to submit HTTP/1.1 requests. There's no need to manually add query strings to your URLs or form-encode your PUT and POST data – simply use the JSON method anymore!

We use the web browsers python module as well, but we don't have to install it. It's part of the standard Python library.

Now it's time to code.

Source Code for Random Wikipedia Article in Python Language

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
        webbrowser.open(url)
        break
    elif ans == "n":
        print("Try again!")
        continue
    else:
        print("Wrong choice!")
        break

As a result of processing this https://en.wikipedia.org/wiki/Special:Random link, the same link could not be used again for opening after receiving the user's choice, hence the link had to be saved before displaying the title.

We utilize a while true loop to incorporate everything here. The final if-else element is then simply left to access the URL depending on the user's decision.
When the user clicks Y, the Wikipedia site will open in the browser with the specified title.

Output

wikipedia

Conclusion

So, this is a python-based random Wikipedia article generator. Now test this code and tell your friends about it.



About the author:
Adarsh Kumar Singh is a technology writer with a passion for coding and programming. With years of experience in the technical field, he has established a reputation as a knowledgeable and insightful writer on a range of technical topics.