Random Wikipedia Article Reader | Rookie Week of Python Day 05

hannankhan

Hannan

Posted on March 24, 2021

Random Wikipedia Article Reader | Rookie Week of Python Day 05

Every person that has ever been bored on the internet and read Wikipedia articles to rid themselves of boredom has probably used their random article generator link:

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

Today we will use this link to write a python script that searches Wikipedia for random articles and gives you a y/n prompt to choose if you'd like to read the article or pick another random article. Since the link can not be refreshed to again search for a different article we will need to use loops.

Random Wiki Article Generator

First we will need to pip install two prerequisites, easily done as follows:

pip install beautifulsoup4
pip install requests

Now to import the above installs and an additional webbrowser module

import requests
from bs4 import BeautifulSoup
import webbrowser
Enter fullscreen mode Exit fullscreen mode

We will declare a while loop and three variable.

  • url - contains the random wiki link
  • soup - used to parse html content
  • title - fetch firstheading value from parsed data
while True:
    url = requests.get("https://en.wikipedia.org/wiki/Special:Random")
    soup = BeautifulSoup(url.content, "html.parser")
    title = soup.find(class_="firstHeading").text
Enter fullscreen mode Exit fullscreen mode

A print statement to prompt the user for a y/n option and an input() statement. Append the statement with the .lower() function to convert any uppercase inputs to lowercase as to avoid any incorrect inputs.

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 read this article? (Y/N)")
    ans = input("").lower()
Enter fullscreen mode Exit fullscreen mode

Write a conditional statement to perform different functionality based on user input. Execute webbrowser.open() to open a browser windows with the selected link (program will use the default browser for this purpose).

if ans == "y":
        url = "https://en.wikipedia.org/wiki/%s" % title
        webbrowser.open(url)
        break
    elif ans == "n":
        print("Don't worry. Fetching a new article for you!")
        continue
    else:
        print("Invalid Command!")
        break
Enter fullscreen mode Exit fullscreen mode

Output

Alt Text

Thank you for reading. You can get the code here from it's GitHub repo.

💖 💪 🙅 🚩
hannankhan
Hannan

Posted on March 24, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related