Python to Save Random Wikipedia Article to Text with Full Source Code For Beginners

An application to save any random article from Wikipedia to a text file.

Install:

pip install htmlparser <code>pip install beautifulsoup4</code>
Code language: HTML, XML (xml)

Requirement:

  • HTMLParser==0.0.2

Source Code:

wiki_random.py

from bs4 import BeautifulSoup import requests # Trying to open a random wikipedia article # Special:Random opens random articles res = requests.get("https://en.wikipedia.org/wiki/Special:Random") res.raise_for_status() # pip install htmlparser wiki = BeautifulSoup(res.text, "html.parser") r = open("random_wiki.txt", "w+", encoding='utf-8') # Adding the heading to the text file heading = wiki.find("h1").text r.write(heading + "\n") for i in wiki.select("p"): # Optional Printing of text # print(i.getText()) r.write(i.getText()) r.close() print("File Saved as random_wiki.txt")
Code language: PHP (php)

Leave a Comment