The Wayback Machine - https://web.archive.org/web/20240914135810/https://www.geeksforgeeks.org/implementing-web-scraping-python-beautiful-soup/
Open In App

Implementing Web Scraping in Python with BeautifulSoup

Last Updated : 02 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

There are mainly two ways to extract data from a website:

  • Use the API of the website (if it exists). For example, Facebook has the Facebook Graph API which allows retrieval of data posted on Facebook.
  • Access the HTML of the webpage and extract useful information/data from it. This technique is called web scraping or web harvesting or web data extraction.

This article discusses the steps involved in web scraping using the implementation of a Web Scraping framework of Python called Beautiful Soup. Steps involved in web scraping:

  1. Send an HTTP request to the URL of the webpage you want to access. The server responds to the request by returning the HTML content of the webpage. For this task, we will use a third-party HTTP library for python-requests.
  2. Once we have accessed the HTML content, we are left with the task of parsing the data. Since most of the HTML data is nested, we cannot extract data simply through string processing. One needs a parser which can create a nested/tree structure of the HTML data. There are many HTML parser libraries available but the most advanced one is html5lib.
  3. Now, all we need to do is navigating and searching the parse tree that we created, i.e. tree traversal. For this task, we will be using another third-party python library, Beautiful Soup. It is a Python library for pulling data out of HTML and XML files.

Step 1: Installing the required third-party libraries

  • Easiest way to install external libraries in python is to use pip. pip is a package management system used to install and manage software packages written in Python. All you need to do is:
pip install requests
pip install html5lib
pip install bs4

Step 2: Accessing the HTML content from webpage 

Python
import requests
URL = "https://www.cdn.geeksforgeeks.org/data-structures/"
r = requests.get(URL)
print(r.content)

Let us try to understand this piece of code.

  • First of all import the requests library.
  • Then, specify the URL of the webpage you want to scrape.
  • Send a HTTP request to the specified URL and save the response from server in a response object called r.
  • Now, as print r.content to get the raw HTML content of the webpage. It is of ‘string’ type.

Note: Sometimes you may get error “Not accepted” so try adding a browser user agent like below. Find your user agent based on device and browser from here https://deviceatlas.com/blog/list-of-user-agent-strings

Python
headers = {'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246"}
# Here the user agent is for Edge browser on windows 10. You can find your browser user agent from the above given link.
r = requests.get(url=URL, headers=headers)
print(r.content)

Step 3: Parsing the HTML content 

Python
#This will not run on online IDE
import requests
from bs4 import BeautifulSoup

URL = "http://www.values.com/inspirational-quotes"
r = requests.get(URL)

soup = BeautifulSoup(r.content, 'html5lib') # If this line causes an error, run 'pip install html5lib' or install html5lib
print(soup.prettify())

A really nice thing about the BeautifulSoup library is that it is built on the top of the HTML parsing libraries like html5lib, lxml, html.parser, etc. So  BeautifulSoup object and specify the parser library can be created at the same time. In the example above,

soup = BeautifulSoup(r.content, 'html5lib')

We create a BeautifulSoup object by passing two arguments:

  • r.content : It is the raw HTML content.
  • html5lib : Specifying the HTML parser we want to use.

Now soup.prettify() is printed, it gives the visual representation of the parse tree created from the raw HTML content. Step 4: Searching and navigating through the parse tree Now, we would like to extract some useful data from the HTML content. The soup object contains all the data in the nested structure which could be programmatically extracted. In our example, we are scraping a webpage consisting of some quotes. So, we would like to create a program to save those quotes (and all relevant information about them). 

Python
#Python program to scrape website 
#and save quotes from website
import requests
from bs4 import BeautifulSoup
import csv
 
URL = "http://www.values.com/inspirational-quotes"
r = requests.get(URL)
 
soup = BeautifulSoup(r.content, 'html5lib')
 
quotes=[]  # a list to store quotes
 
table = soup.find('div', attrs = {'id':'all_quotes'}) 
 
for row in table.findAll('div',
                         attrs = {'class':'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}):
    quote = {}
    quote['theme'] = row.h5.text
    quote['url'] = row.a['href']
    quote['img'] = row.img['src']
    quote['lines'] = row.img['alt'].split(" #")[0]
    quote['author'] = row.img['alt'].split(" #")[1]
    quotes.append(quote)
 
filename = 'inspirational_quotes.csv'
with open(filename, 'w', newline='') as f:
    w = csv.DictWriter(f,['theme','url','img','lines','author'])
    w.writeheader()
    for quote in quotes:
        w.writerow(quote)

Before moving on, we recommend you to go through the HTML content of the webpage which we printed using soup.prettify() method and try to find a pattern or a way to navigate to the quotes.

  • It is noticed that all the quotes are inside a div container whose id is ‘all_quotes’. So, we find that div element (termed as table in above code) using find() method :
table = soup.find('div', attrs = {'id':'all_quotes'}) 
  • The first argument is the HTML tag you want to search and second argument is a dictionary type element to specify the additional attributes associated with that tag. find() method returns the first matching element. You can try to print table.prettify() to get a sense of what this piece of code does.
  • Now, in the table element, one can notice that each quote is inside a div container whose class is quote. So, we iterate through each div container whose class is quote. Here, we use findAll() method which is similar to find method in terms of arguments but it returns a list of all matching elements. Each quote is now iterated using a variable called row. Here is one sample row HTML content for better understanding: Implementing Web Scraping in Python with Beautiful Soup Now consider this piece of code:
for row in table.find_all_next('div', attrs = {'class': 'col-6 col-lg-3 text-center margin-30px-bottom sm-margin-30px-top'}):
quote = {}
quote['theme'] = row.h5.text
quote['url'] = row.a['href']
quote['img'] = row.img['src']
quote['lines'] = row.img['alt'].split(" #")[0]
quote['author'] = row.img['alt'].split(" #")[1]
quotes.append(quote)
  • We create a dictionary to save all information about a quote. The nested structure can be accessed using dot notation. To access the text inside an HTML element, we use .text : 
quote['theme'] = row.h5.text
  • We can add, remove, modify and access a tag’s attributes. This is done by treating the tag as a dictionary:
quote['url'] = row.a['href']
  • Lastly, all the quotes are appended to the list called quotes.
  • Finally, we would like to save all our data in some CSV file.
filename = 'inspirational_quotes.csv'
with open(filename, 'w', newline='') as f:
w = csv.DictWriter(f,['theme','url','img','lines','author'])
w.writeheader()
for quote in quotes:
w.writerow(quote)
  • Here we create a CSV file called inspirational_quotes.csv and save all the quotes in it for any further use.

So, this was a simple example of how to create a web scraper in Python.  From here, you can try to scrap any other website of your choice. In case of any queries, post them below in comments section.

Note : Web Scraping is considered as illegal in many cases. It may also cause your IP to be blocked permanently by a website. This blog is contributed by Nikhil Kumar.

Implementing Web Scraping in Python with BeautifulSoup – FAQs

How to Use BeautifulSoup for Web Scraping in Python?

BeautifulSoup is a powerful library in Python used for web scraping purposes. It helps in parsing HTML and XML documents, making it easy to navigate, search, and modify the parse tree.

Example of Using BeautifulSoup:

from bs4 import BeautifulSoup
import requests

# Fetch the web page
url = "https://example.com"
response = requests.get(url)
data = response.text

# Parse the HTML content
soup = BeautifulSoup(data, 'html.parser')

# Extract specific elements
titles = soup.find_all('h1')
for title in titles:
print(title.text)

This script fetches an HTML page, parses it, and prints out all text within <h1> tags.

What is the Use of BeautifulSoup?

BeautifulSoup is used for parsing HTML and XML documents. It is commonly used to extract information from web pages, such as gathering data from various elements within the HTML structure of the page.

Is BeautifulSoup Good for Web Scraping?

Yes, BeautifulSoup is excellent for web scraping due to its ability to parse complex HTML content and its user-friendly methods for navigating and searching the parse tree. It can handle various markup formats and provides simple methods for extracting data, which makes it a popular choice among Python developers for web scraping tasks.

Why is it Called BeautifulSoup?

The name “BeautifulSoup” is whimsical, reflecting the library’s ability to turn “markup soup” — which is often how real-world HTML documents are described due to their messy and inconsistent nature — into a structured format that is easy to work with. It effectively “beautifies” this “soup” of code.

Which Tool is Best for Web Scraping?

The best tool for web scraping often depends on the specific needs of the project:

  • BeautifulSoup: Best for simple HTML data extraction and when learning web scraping. It’s user-friendly but can be slower with large or complex websites.
  • Scrapy: More powerful and faster, suitable for large-scale web scraping and handling requests asynchronously. It also provides built-in support for generating feed exports in various formats and maintaining statistics.
  • Selenium: Ideal for websites that require interacting with JavaScript since it can automate a real browser, allowing it to execute JavaScript just as a human user might.

Each tool has its strengths and is best suited to different types of scraping tasks. BeautifulSoup is often enough for basic projects and is an excellent tool for beginners due to its simplicity and ease of use.



    Similar Reads

    Web Scraping using Beautifulsoup and scrapingdog API
    In this post we are going to scrape dynamic websites that use JavaScript libraries like React.js, Vue.js, Angular.js, etc you have to put extra efforts. It is an easy but lengthy process if you are going to install all the libraries like Selenium, Puppeteer, and headerless browsers like Phantom.js. But, we have a tool that can handle all this load
    5 min read
    Implementing web scraping using lxml in Python
    Web scraping basically refers to fetching only some important piece of information from one or more websites. Every website has recognizable structure/pattern of HTML elements. Steps to perform web scraping :1. Send a link and get the response from the sent link 2. Then convert response object to a byte string. 3. Pass the byte string to 'fromstrin
    3 min read
    BeautifulSoup object - Python Beautifulsoup
    BeautifulSoup object is provided by Beautiful Soup which is a web scraping framework for Python. Web scraping is the process of extracting data from the website using automated tools to make the process faster. The BeautifulSoup object represents the parsed document as a whole. For most purposes, you can treat it as a Tag object. Syntax: BeautifulS
    2 min read
    Scraping Reddit with Python and BeautifulSoup
    In this article, we are going to see how to scrape Reddit with Python and BeautifulSoup. Here we will use Beautiful Soup and the request module to scrape the data. Module neededbs4: 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 comma
    3 min read
    BeautifulSoup - Scraping List from HTML
    Prerequisite: RequestsBeautifulSoup Python can be employed to scrap information from a web page. It can also be used to retrieve data provided within a specific tag, this article how list elements can be scraped from HTML. Module Needed: bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not co
    2 min read
    BeautifulSoup - Scraping Paragraphs from HTML
    In this article, we will discuss how to scrap paragraphs from HTML using Beautiful Soup Method 1: using bs4 and urllib. Module Needed: bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. For installing the module-pip install bs4.urllib: urllib is a package that collects several modules for working with URLs. It
    3 min read
    BeautifulSoup - Scraping Link from HTML
    Prerequisite: Implementing Web Scraping in Python with BeautifulSoup In this article, we will understand how we can extract all the links from a URL or an HTML document using Python. Libraries Required:bs4 (BeautifulSoup): It is a library in python which makes it easy to scrape information from web pages, and helps in extracting the data from HTML
    2 min read
    Web Scraping CryptoCurrency price and storing it in MongoDB using Python
    Let us see how to fetch history price in USD or BTC, traded volume and market cap for a given date range using Santiment API and storing the data into MongoDB collection. Python is a mature language and getting much used in the Cryptocurrency domain. MongoDB is a NoSQL database getting paired with Python in many projects which helps to hold details
    4 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
    Quote Guessing Game using Web Scraping in Python
    Prerequisite: BeautifulSoup Installation In this article, we will scrape a quote and details of the author from this site http//quotes.toscrape.com using python framework called BeautifulSoup and develop a guessing game using different data structures and algorithm. The user will be given 4 chances to guess the author of a famous quote, In every ch
    3 min read
    How to Build Web scraping bot in Python
    In this article, we are going to see how to build a web scraping bot in Python. Web Scraping is a process of extracting data from websites. A Bot is a piece of code that will automate our task. Therefore, A web scraping bot is a program that will automatically scrape a website for data, based on our requirements. Module neededbs4: Beautiful Soup(bs
    8 min read
    Clean Web Scraping Data Using clean-text in Python
    If you like to play with API's or like to scrape data from various websites, you must've come around random annoying text, numbers, keywords that come around with data. Sometimes it can be really complicating and frustrating to clean scraped data to obtain the actual data that we want. In this article, we are going to explore a python library calle
    2 min read
    Web Scraping Financial News Using Python
    In this article, we will cover how to extract financial news seamlessly using Python. This financial news helps many traders in placing the trade in cryptocurrency, bitcoins, the stock markets, and many other global stock markets setting up of trading bot will help us to analyze the data. Thus all this can be done with the help of web scraping usin
    3 min read
    Web Scraping Tables with Selenium and Python
    Selenium is the automation software testing tool that obtains the website, performs various actions, or obtains the data from the website. It was chiefly developed for easing the testing work by automating web applications. Nowadays, apart from being used for testing, it can also be used for making tedious work interesting. Do you know that with th
    4 min read
    Pagination using Scrapy - Web Scraping with Python
    Pagination using Scrapy. Web scraping is a technique to fetch information from websites. Scrapy is used as a Python framework for web scraping. Getting data from a normal website is easier, and can be just achieved by just pulling the HTML of the website and fetching data by filtering tags. But what is the case when there is Pagination in Python an
    3 min read
    Reading selected webpage content using Python Web Scraping
    Prerequisite: Downloading files in Python, Web Scraping with BeautifulSoup We all know that Python is a very easy programming language but what makes it cool are the great number of open source library written for it. Requests is one of the most widely used library. It allows us to open any HTTP/HTTPS website and let us do any kind of stuff we norm
    3 min read
    Spoofing IP address when web scraping using Python
    In this article, we are going to scrap a website using Requests by rotating proxies in Python. Modules RequiredRequests module allows you to send HTTP requests and returns a response with all the data such as status, page content, etc. Syntax: requests.get(url, parameter) JSON JavaScript Object Notation is a format for structuring data. It is mainl
    3 min read
    Python | Tools in the world of Web Scraping
    Web page scraping can be done using multiple tools or using different frameworks in Python. There are variety of options available for scraping data from a web page, each suiting different needs. First, let's understand the difference between web-scraping and web-crawling. Web crawling is used to index the information on the page using bots also kn
    4 min read
    Increase the speed of Web Scraping in Python using HTTPX module
    In this article, we will talk about how to speed up web scraping using the requests module with the help of the HTTPX module and AsyncIO by fetching the requests concurrently. The user must be familiar with Python. Knowledge about the Requests module or web scraping would be a bonus. Required Module For this tutorial, we will use 4 modules - timere
    4 min read
    Web Scraping for Stock Prices in Python
    Web scraping is a data extraction method that collects data only from websites. It is often used for data mining and gathering valuable insights from large websites. Web scraping is also useful for personal use. Python includes a nice library called BeautifulSoup that enables web scraping. In this article, we will extract current stock prices using
    6 min read
    Web Scraping - Legal or Illegal?
    If you're connected with the term 'Web Scraping' anyhow, then you must come across a question - Is Web Scraping legal or illegal? Okay, so let's discuss it. If you look closely, you will find out that in today's era the biggest asset of any business is Data! Even the top giants like Facebook, Amazon, Uber are ruling because of the vast amount of da
    5 min read
    Web Scraping Coronavirus Data into MS Excel
    Prerequisites: Web Scraping using BeautifulSoup Coronavirus cases are increasing rapidly worldwide. This article will guide you on how to web scrape Coronavirus data and into Ms-excel. What is Web Scraping? If you’ve ever copy and pasted information from a website, you’ve performed the same function as any web scraper, only on a microscopic, manual
    5 min read
    Web Scraping - Amazon Customer Reviews
    In this article, we are going to see how we can scrape the amazon customer review using Beautiful Soup in Python. Module neededbs4: 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: Requ
    5 min read
    Web Scraping Without Getting Blocked
    Web Scraping refers to the process of scraping/extracting data from a website using the HTTP protocol or web browser. The process can either be manual or it can be automated using a bot or a web crawler. Also, there is a misconception about web scraping being illegal, the truth is that it is perfectly legal unless you're trying to access non-public
    7 min read
    How to not get caught while web scraping ?
    In this article, we are going to discuss how to not get caught while web scraping. Let's look at all such alternatives in detail: Robots.txtIt is a text file created by the webmaster which tells the search engine crawlers which pages are allowed to be crawled by the bot, so it is better to respect robots.txt before scraping.Example: Here GFG's robo
    5 min read
    Web Scraping in Flutter
    The process of extracting required data/information from a web page by accessing the HTML of the web page is called Web Scraping or Web Harvesting or Web Data Extraction. This article discusses the steps involved in Web Scraping by using Flutter's html and http packages. Step 1: Set up a new Flutter App Create a new flutter app by running the comma
    6 min read
    10 Best Web Scraping Tools
    In today's vast world of data and decision-making, web scraping has become an invaluable technique for extracting information from websites. Whether you're a data enthusiast, a researcher, or a business professional, having the right web scraping tools at your end can greatly enhance your data-gathering capabilities. Before moving ahead in this art
    11 min read
    The Complete Guide to Proxies For Web Scraping
    In computer networking, a proxy server is a server application or appliance that acts as an intermediary for requests from clients seeking resources from servers that provide those resources. Since web scraping requires a lot of requests made to a server from an IP address, the server may detect too many requests and may block the IP address to sto
    5 min read
    Create Cricket Score API using Web Scraping in Flask
    Cricket is one of the famous outdoor sport played worldwide. There are very few APIs providing live scoreboards and none of them are free to use. Using any of the scoreboards available we can create API for ourselves. This method not only works for Cricket Scoreboard but also for any information available online. Following is the flow in which this
    6 min read
    What is Web Scraping and How to Use It?
    Suppose you want some information from a website. Let’s say a paragraph on Donald Trump! What do you do? Well, you can copy and paste the information from Wikipedia into your file. But what if you want to get large amounts of information from a website as quickly as possible? Such as large amounts of data from a website to train a Machine Learning
    7 min read
    Article Tags :
    Practice Tags :