The Wayback Machine - https://web.archive.org/web/20261124174243/https://www.geeksforgeeks.org/python/implementing-web-scraping-python-beautiful-soup/

Implementing Web Scraping in Python with BeautifulSoup

Last Updated : 4 Nov, 2026

Web scraping is the process of automatically extracting information from websites. Python provides libraries such as Requests and Beautiful Soup to fetch webpage content, parse HTML and extract specific data.

In this article, we will implement web scraping using Beautiful Soup, extract quotes and their authors from a website designed for scraping practice, and save the results in a CSV file.

Installation

install Requests and Beautiful Soup using the following command.

python -m pip install requests beautifulsoup4

Explanation:

  • requests installs the library used to fetch webpage content.
  • beautifulsoup4 installs the library used to parse HTML and XML.
  • csv module used later is included in Python's standard library, so no additional installation is required.

1. Fetching HTML Content Using Requests

The first step is to send an HTTP GET request to the target website. For this example, we will use Quotes to Scrape, a website intended for practicing web scraping.

Python
import requests

url = "https://quotes.toscrape.com/"

response = requests.get(url, timeout=10)
response.raise_for_status()

print(response.status_code)
print(response.text[:500])

Output

Screenshot_2026-10-22_16-23-35
Output

Explanation:

  • requests.get() sends a GET request to retrieve the webpage.
  • Timeout parameter prevents the request from waiting indefinitely for a response.
  • raise_for_status() raises an exception if the server returns an unsuccessful HTTP status code.
  • response.status_code displays the HTTP status, while response.text contains the response body as text.

2. Parse HTML Using Beautiful Soup

Response contains the page's HTML as text. Beautiful Soup converts this content into a structured representation that can be searched using different methods.

Python
from bs4 import BeautifulSoup

soup = BeautifulSoup(response.text, "html.parser")

print(soup.title.get_text(strip=True))

Output

Quotes to Scrape

Explanation:

  • BeautifulSoup() accepts the HTML content and the parser to use.
  • html.parser is Python's built-in HTML parser.
  • soup.title locates the page's title element.
  • get_text(strip=True) extracts its text and removes surrounding whitespace.

3. Inspecting HTML Structure

Before extracting information, inspect the HTML to understand how the required data is organized. This helps identify the correct tags, classes and attributes.

Python
print(soup.prettify()[:2000])

Output

Screenshot_2026-10-22_16-27-31
Output

Explanation:

  • prettify() formats the parsed HTML with indentation for easier inspection.
  • slice displays only the first 2,000 characters instead of printing the entire document.
  • Look for the HTML elements that contain the information you need.

4. Finding Specific Elements Using Beautiful Soup

It provides several methods for locating HTML elements. The find() method returns the first matching element, while find_all() returns all matching elements. It also supports CSS selectors through select() and select_one(). These methods are useful when elements are identified by classes, IDs or their position within the HTML structure.

Examples:

Python
quote_cards = soup.select("div.quote")

for card in quote_cards:
    quote = card.select_one("span.text")
    author = card.select_one("small.author")

    if quote and author:
        print(quote.get_text(strip=True))
        print(author.get_text(strip=True))
        print()

Output

Screenshot_2026-10-22_16-33-01
Output

Explanation:

  • select("div.quote") locates all elements representing individual quotes.
  • select_one("span.text") retrieves the quote text within a card.
  • select_one("small.author") retrieves the author's name.
  • get_text(strip=True) extracts clean text from the selected elements.
  • Condition checks that both elements exist before extracting their content.

5. Extracting and Organize Data

After locating the required elements, store their information in Python dictionaries. A list of dictionaries keeps each quote, author and associated tags together.

Python
quotes = []

for card in soup.select("div.quote"):
    quote_element = card.select_one("span.text")
    author_element = card.select_one("small.author")

    if quote_element is None or author_element is None:
        continue

    tags = [
        tag.get_text(strip=True)
        for tag in card.select("a.tag")
    ]

    quotes.append({
        "quote": quote_element.get_text(strip=True),
        "author": author_element.get_text(strip=True),
        "tags": ", ".join(tags)
    })

for item in quotes[:3]:
    print(item)

Output

{'quote': '“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”', 'author': 'Albert Einstein', 'tags': 'change, deep-thoughts, thinking, world'}
{'quote': '“It is our choices, Harry, that show what we truly are, far more than our abilities.”', 'author': 'J.K. Rowling', 'tags': 'abilities, choices'}
{'quote': '“There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.”', 'author': 'Albert Einstein', 'tags': 'inspirational, life, live, miracle, miracles'}

Explanation:

  • An empty list stores the extracted records.
  • Each quote card is processed separately.
  • Missing quote or author elements are skipped.
  • List comprehension extracts all tags associated with a quote.
  • Each dictionary stores the quote, author and comma-separated tags.
  • Final loop displays the first three records for verification.

6. Saving the Extracted Data to CSV

CSV files store tabular data in rows and columns, making them useful for analysis in spreadsheet applications or Python libraries such as Pandas. Python's built-in csv module provides DictWriter to write dictionaries into a CSV file.

Python
import csv

fieldnames = ["quote", "author", "tags"]

with open(
    "quotes.csv",
    "w",
    newline="",
    encoding="utf-8"
) as file:
    writer = csv.DictWriter(file, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerows(quotes)

print(f"Saved {len(quotes)} quotes to quotes.csv")

Output

Saved 10 Quotes in quotes.csv

Explanation:

  • open() creates quotes.csv in write mode.
  • newline="" helps prevent unwanted blank lines when writing CSV records.
  • encoding="utf-8" supports a wide range of characters.
  • csv.DictWriter() maps dictionary keys to the specified columns.
  • writeheader() writes the column names.
  • writerows() writes all extracted dictionaries to the file.
  • Final statement reports how many records were saved.
Comment