The Wayback Machine - https://web.archive.org/web/20241119172621/https://www.geeksforgeeks.org/how-to-extract-wikipedia-data-in-python/
Open In App

How to Extract Wikipedia Data in Python?

Last Updated : 11 Feb, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article we will learn how to extract Wikipedia Data Using Python, Here we use two methods for extracting Data.

Method 1: Using Wikipedia module

In this method, we will use the Wikipedia Module for Extracting Data. Wikipedia is a multilingual online encyclopedia created and maintained as an open collaboration project by a community of volunteer editors using a wiki-based editing system.

For installation run this command into your terminal.

pip install wikipedia

Wikipedia Data, we will be extracted here:-

  • Summary, title
  • Page Content
  • Get the list of Image Source and Page URL
  • Different categories

Extract Data one by one:

1. Extracting summary and page

Syntax: wikipedia.summary(“Enter Query”)
 

wikipedia.page(“Enter Query”).title

Python3




import wikipedia
 
 
wikipedia.summary("Python (programming language)")


Output:

2. Page Content: 

For extracting the content of an article, we will use page() method and content property to get the actual data.

Syntax: wikipedia.page(“Enter Query”).content

Python3




wikipedia.page("Python (programming language)").content


Output:

3. Extract images from Wikipedia.

Syntax: wikipedia.page(“Enter Query”).images

Python3




wikipedia.page("Python (programming language)").images


Output: 

4. extract current Page URL: 

Use page() method and url property. 

Syntax: wikipedia.page(“Enter Query”).url

Python3




wikipedia.page('"Hello, World!" program').url


Output: 

'https://en.wikipedia.org/wiki/%22Hello,_World!%22_program'

5. Get the list of categories of articles.

Use page() method and categories property. 

Syntax: wikipedia.page(“Enter Query”).categories

Python3




wikipedia.page('"Hello, World!" program').categories


Output: 

['Articles with example code',
 'Articles with short description',
 'Commons category link is on Wikidata',
 'Computer programming folklore',
 'Short description is different from Wikidata',
 'Test items in computer languages',
 'Webarchive template wayback links']

6. Get the list of all links to an article 

Syntax: wikipedia.page(“Enter Query”).links

Python3




wikipedia.page('"Hello, World!" program').links


Output: 

7. Get data in different languages.

Now we will see language conversion, for converting into another language we will use set_lang() method. 

Syntax: wikipedia.set_lang(“Enter Language Type”)

Python3




wikipedia.set_lang("hi")
wikipedia.summary('"Hello, World!" program')


Output:
 

Method 2: Using Requests, BeautifulSoup

In this method, we will use Web Scraping.

For scraping in Python we will use two modules:

  • bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal.
pip install bs4
  • requests: Requests allow you to send HTTP/1.1 requests extremely easily. This module also does not comes built-in with Python. To install this type the below command in the terminal.
pip install requests

Data will be extracted:- 

  • Paragraphs
  • Images
  • List of Images
  • Headings
  • Unwanted Content (Remaining Content)

Approach: 

  • Get HTML Code
  • From HTML Code, get the content of inside body tag
  • Iterate 

Python3




# Import Module
from bs4 import *
import requests
 
# Given URL
 
# Fetch URL Content
r = requests.get(url)
 
# Get body content
soup = BeautifulSoup(r.text,'html.parser').select('body')[0]
 
# Initialize variable
paragraphs = []
images = []
link = []
heading = []
remaining_content = []
 
# Iterate through all tags
for tag in soup.find_all():
     
    # Check each tag name
    # For Paragraph use p tag
    if tag.name=="p":
       
        # use text for fetch the content inside p tag
        paragraphs.append(tag.text)
         
    # For Image use img tag
    elif tag.name=="img":
       
        # Add url and Image source URL
        images.append(url+tag['src'])
         
    # For Anchor use a tag
    elif tag.name=="a":
       
        # convert into string and then check href
        # available in tag or not
        if "href" in str(tag):
           
          # In href, there might be possible url is not there
          # if url is not there
            if "https://en.wikipedia.org/w/" not in str(tag['href']):
                link.append(url+tag['href'])
            else:
                link.append(tag['href'])
                 
    # Similarly check for heading
    # Six types of heading are there (H1, H2, H3, H4, H5, H6)
    # check each tag and fetch text
    elif "h" in tag.name:
        if "h1"==tag.name:
            heading.append(tag.text)
        elif "h2"==tag.name:
            heading.append(tag.text)
        elif "h3"==tag.name:
            heading.append(tag.text)
        elif "h4"==tag.name:
            heading.append(tag.text)
        elif "h5"==tag.name:
            heading.append(tag.text)
        else:
            heading.append(tag.text)
             
    # Remain content will store here
    else:
        remaining_content.append(tag.text)
         
print(paragraphs, images, link, heading, remaining_content)


  •  body content and fetch the above data

Below is the full implementation: 

Python3




# Import Module
from bs4 import *
import requests
 
# Given URL
 
# Fetch URL Content
r = requests.get(url)
 
# Get body content
soup = BeautifulSoup(r.text,'html.parser').select('body')[0]
 
# Initialize variable
paragraphs = []
images = []
link = []
heading = []
remaining_content = []
 
# Iterate through all tags
for tag in soup.find_all():
     
    # Check each tag name
    # For Paragraph use p tag
    if tag.name=="p":
       
        # use text for fetch the content inside p tag
        paragraphs.append(tag.text)
         
    # For Image use img tag
    elif tag.name=="img":
       
        # Add url and Image source URL
        images.append(url+tag['src'])
         
    # For Anchor use a tag
    elif tag.name=="a":
       
        # convert into string and then check href
        # available in tag or not
        if "href" in str(tag):
           
          # In href, there might be possible url is not there
          # if url is not there
            if "https://en.wikipedia.org/w/" not in str(tag['href']):
                link.append(url+tag['href'])
            else:
                link.append(tag['href'])
                 
    # Similarly check for heading
    # Six types of heading are there (H1, H2, H3, H4, H5, H6)
    # check each tag and fetch text
    elif "h" in tag.name:
        if "h1"==tag.name:
            heading.append(tag.text)
        elif "h2"==tag.name:
            heading.append(tag.text)
        elif "h3"==tag.name:
            heading.append(tag.text)
        elif "h4"==tag.name:
            heading.append(tag.text)
        elif "h5"==tag.name:
            heading.append(tag.text)
        else:
            heading.append(tag.text)
             
    # Remain content will store here
    else:
        remaining_content.append(tag.text)
         
print(paragraphs, images, link, heading, remaining_content)


Example: 

 



Previous Article
Next Article

Similar Reads

Fetching text from Wikipedia's Infobox in Python
An infobox is a template used to collect and present a subset of information about its subject. It can be described as a structured document containing a set of attribute-value pairs, and in Wikipedia, it represents a summary of information about the subject of an article.So a Wikipedia infobox is a fixed-format table usually added to the top right
3 min read
Voice search Wikipedia using Python
Every day, we visit so many applications, be it messaging platforms like Messenger, Telegram or ordering products on Amazon, Flipkart, or knowing about weather and the list can go on. And we see that these websites have their own software program for initiating conversations with human beings using rules or artificial intelligence. Users interact w
5 min read
Wikipedia module in Python
The Internet is the single largest source of information, and therefore it is important to know how to fetch data from various sources. And with Wikipedia being one of the largest and most popular sources for information on the Internet. Wikipedia is a multilingual online encyclopedia created and maintained as an open collaboration project by a com
3 min read
Web scraping from Wikipedia using Python - A Complete Guide
In this article, you will learn various concepts of web scraping and get comfortable with scraping various types of websites and their data. The goal is to scrape data from the Wikipedia Home page and parse it through various web scraping techniques. You will be getting familiar with various web scraping techniques, python modules for web scraping,
9 min read
Wikipedia Summary Generator using Python Tkinter
Prerequisite: Tkinter Wikipedia Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. Wikipedia is a Python library that makes it easy to access and parse data from "wiki
2 min read
Wikipedia search app using Flask Framework - Python
Flask is a micro web framework written in Python. It is classified as a micro-framework because it does not require particular tools or libraries. Flask is a lightweight WSGI web application framework. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. Installation: 1) In order to create the
2 min read
Wikipedia search app Project using Django
Django is a high-level Python based Web Framework that allows rapid development and clean, pragmatic design. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. Today we will create joke app in django. In this article we will make
2 min read
Scraping Wikipedia table with Pandas using read_html()
In this article, we will discuss a particular function named read_html() which is used to read HTML tables directly from a webpage into a Pandas DataFrame without knowing how to scrape a website's HTML, this tool can be useful for swiftly combining tables from numerous websites. However, the data must have to be cleaned further, So let's see how we
3 min read
Extract Data from Database using MySQL-Connector and XAMPP in Python
Prerequisites: MySQL-Connector, XAMPP Installation A connector is employed when we have to use MySQL with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. RequirementsXAMPP: Database / Server
2 min read
How to extract youtube data in Python?
Prerequisites: Beautifulsoup YouTube statistics of a YouTube channel can be used for analysis and it can also be extracted using python code. A lot of data like viewCount, subscriberCount, and videoCount can be retrieved. This article discusses 2 ways in which this can be done. Method 1: Using YouTube API First we need to generate an API key. You n
3 min read
How To Extract Data From Common File Formats in Python?
Sometimes work with some datasets must have mostly worked with .csv(Comma Separated Value) files only. They are really a great starting point in applying Data Science techniques and algorithms. But many of us will land up in Data Science firms or take up real-world projects in Data Science sooner or later. Unfortunately in real-world projects, the
6 min read
Extract Data from PGN Files Using the Chess Library in Python
In this article, we are going to see how to extract data from PGN Files using the chess library in Python. With the help of the chess library in python, we can perform several operations like validating a move, extracting data, and even making moves on the chessboard. In this article, we will extract data from a PGN file or a PGN string using the p
6 min read
How to Extract Weather Data from Google in Python?
In this article, we will see how to extract weather data from google. Google does not have its own weather API, it fetches data from weather.com and shows it when you search on Google. So, we will scrape the data from Google, and also we will see another method to fetch a schematic depiction of a location's weather data for the next two days in Pyt
4 min read
How to extract Time data from an Excel file column using Pandas?
Prerequisite: Regular Expressions in Python In these articles, we will discuss how to extract Time data from an Excel file column using Pandas. Suppose our Excel file looks like below given image then we have to extract the Time from the Excel sheet column and store it into a new Dataframe column. For viewing the Excel file Click Here. Approach: Im
2 min read
How to extract the data from an ImmutableMultiDict
Perquisites : ImmutableMultiDict In this article, we are going to use ImmutableMultiDict to extract the data using Python, which is a type of Dictionary in which a single key can have different values. It is used because some form elements have multiple values for the same key and it saves the multiple values of a key in form of a list. Examples 1:
1 min read
Extract Dictionary Value from Column in Data Frame
Data Frames in Python, especially with libraries like Pandas, are powerful tools for data manipulation and analysis. Sometimes, data stored within a Data Frame's column may be in the form of dictionaries. Extracting values from such dictionaries is a common operation in data preprocessing. This post explores various methods to extract dictionary va
3 min read
Python Regex to extract maximum numeric value from a string
Given an alphanumeric string, extract maximum numeric value from that string. Alphabets will only be in lower case. Examples: Input : 100klh564abc365bgOutput : 564Maximum numeric value among 100, 564 and 365 is 564.Input : abchsd0sdhsOutput : 0Python Regex to extract maximum numeric value from a stringThis problem has existing solution please refer
2 min read
Python Slicing | Extract ‘k’ bits from a given position
How to extract ‘k’ bits from a given position ‘p’ in a number? Examples: Input : number = 171 k = 5 p = 2 Output : The extracted number is 21 171 is represented as 10101011 in binary, so, you should get only 10101 i.e. 21. Input : number = 72 k = 5 p = 1 Output : The extracted number is 8 72 is represented as 1001000 in binary, so, you should get o
4 min read
How to extract image information from YouTube Playlist using Python?
Prerequisite: YouTube API Google provides a large set of APIs for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Data API is very simple to use provides features like – Search for videosHandle videos like retrieve information about a video, insert a video, delete a video, et
2 min read
Extract CSS tag from a given HTML using Python
Prerequisite: Implementing Web Scraping in Python with BeautifulSoup In this article, we are going to see how to extract CSS from an HTML document or URL using python. Module Needed: bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below
2 min read
Draw a rectangular shape and extract objects using Python's OpenCV
OpenCV is an open-source computer vision and machine learning software library. Various image processing operations such as manipulating images and applying tons of filters can be done with the help of it. It is broadly used in Object detection, Face Detection, and other Image processing tasks. Let's see how to draw rectangular shape on image and e
4 min read
Extract images from video in Python
OpenCV comes with many powerful video editing functions. In current scenario, techniques such as image scanning, face recognition can be accomplished using OpenCV. Image Analysis is a very common field in the area of Computer Vision. It is the extraction of meaningful information from videos or images. OpenCv library can be used to perform multiple
2 min read
Python | Extract URL from HTML using lxml
Link extraction is a very common task when dealing with the HTML parsing. For every general web crawler that's the most important function to perform. Out of all the Python libraries present out there, lxml is one of the best to work with. As explained in this article, lxml provides a number of helper function in order to extract the links. lxml in
4 min read
Python | Extract Combination Mapping in two lists
Sometimes, while working with Python lists, we can have a problem in which we have two lists and require to find the all possible mappings possible in all combinations. This can have possible application in mathematical problems. Let's discuss certain way in which this problem can be solved. Method : Using zip() + product() With these functions thi
2 min read
Extract numbers from a text file and add them using Python
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Data file handling in Python is done in two types of files: Text file (.txt extension) Binary file (.bin extension) Here we are operating on the .txt file in Python. Through this program
4 min read
How to extract Audio Wave from a mixture of Signal using Scipy - Python?
Prerequisites: Scipy Spectral Analysis refers to analyzing of the frequency spectrum/response of the waves. This article as the title suggests deals with extracting audio wave from a mixture of signals and what exactly goes into the process can be explained as: Consider we have 3 mixed Audio Signals having frequency of 50Hz,1023Hz & 1735Hz resp
7 min read
Extract week number from date in Pandas-Python
Many times, when working with some data containing dates we may need to extract the week number from a particular date. In Python, it can be easily done with the help of pandas. Example 1: C/C++ Code # importing pandas as pd import pandas as pd # creating a dictionary containing a date dict = {'Date':["2015-06-17"]} # converting t
2 min read
Extract IP address from file using Python
Let us see how to extract IP addresses from a file using Python. Algorithm : Import the re module for regular expression.Open the file using the open() function.Read all the lines in the file and store them in a list.Declare the pattern for IP addresses. The regex pattern is : r'(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'For every element of the list sea
2 min read
Extract dominant colors of an image using Python
Let us see how to extract the dominant colors of an image using Python. Clustering is used in many real-world applications, one such real-world example of clustering is extracting dominant colors from an image. Any image consists of pixels, each pixel represents a dot in an image. A pixel contains three values and each value ranges between 0 to 255
7 min read
Build an Application to extract URL and Metadata from a PDF using Python
The PDF (Portable Document Format) is the most common use platform-independent file format developed by Adobe to present documents. There are lots of PDF-related packages for Python, one of them is the pdfx module. The pdfx module is used to extract URL, MetaData, and Plain text from a given PDF or PDF URL. Features: Extract references and metadata
3 min read
three90RightbarBannerImg