Automation

Web Scraping with Python: BeautifulSoup Tutorial

Learn how to perform web scraping using Python and BeautifulSoup to extract data and save it to CSV files.

4 min read

Learn how to perform web scraping using Python and BeautifulSoup to extract data from HTML documents and save the results into a CSV file. This guide will walk you through setup, creating a scraping script, and handling your data responsibly.

Prerequisites

Before starting, ensure your environment is ready with the following tools:

prerequisites

  • Python 3.x: Make sure Python version 3.x is installed. Verify with python --version.
  • pip: Installed to manage Python packages.
  • Text Editor or IDE: Such as Visual Studio Code or PyCharm.
  • Libraries: Install the following using pip:
    bash
    pip install beautifulsoup4 lxml requests

Steps to Set Up the Script

This section helps you create a Python script for web scraping.

steps

  1. Create a Python script (scraper.py): Open your text editor or IDE and create a new Python file called scraper.py.

  2. Import necessary libraries: At the beginning of the file, import the required Python modules:

    python
    from bs4 import BeautifulSoup
    import requests
    import csv
  3. Fetch an HTML file or use a local file for testing:

    • For live websites: Use the requests library to fetch the website's HTML content.
    • For local HTML files: Open and read the file into your script.
  4. Load HTML content into BeautifulSoup: To parse and work with the HTML:

    python
    with open("sample.html", "r") as html_file:
        content = html_file.read()
    soup = BeautifulSoup(content, 'lxml')
  5. Identify the elements to scrape:

    • Use soup.find() or soup.find_all() to locate elements by HTML tag names or CSS class names.
    • For example:
    python
    titles = soup.find_all('h5', class_='course-title')
  6. Extract data: Extract the text or attributes from the HTML elements:

    python
    for title in titles:
        print(title.text)

Each step above builds towards crafting a workable scraping script.

Example Script: Extracting Data

Below is a minimal script demonstrating BeautifulSoup's usage to scrape and save data to a CSV file.

scraper.py

```python
from bs4 import BeautifulSoup
import requests
import csv

# Fetch the HTML of the webpage
url = 'http://example.com/sample-webpage'
response = requests.get(url)
html_content = response.text

# Parse the HTML content with BeautifulSoup
soup = BeautifulSoup(html_content, 'lxml')

# Extract data - e.g., course titles and prices
courses = soup.find_all('div', class_='course-card')
data = []
for course in courses:
    title = course.find('h5', class_='course-title').text.strip()
    price = course.find('span', class_='course-price').text.strip()
    data.append([title, price])

# Write the scraped data to a CSV file
with open('courses.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['Title', 'Price'])
    writer.writerows(data)

print("Data saved to courses.csv.")
```

Cautions and Best Practices

When scraping websites, follow these essential ethical and technical practices:

Saving Extracted Data to CSV

Once data is extracted, save it in a structured format like CSV for reuse or analysis.

steps

  1. Structure your data: Create a list of lists where each sublist represents a row of data:

    python
    data = [['Python Basics', '$20'], ['Django Web Development', '$25']]
  2. Write the data to CSV: Use Python's built-in csv module:

    python
    import csv
    
    with open('courses.csv', 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(['Title', 'Price'])  # Header row
        writer.writerows(data)
  3. Verify CSV output: Check the saved courses.csv file to ensure the data is formatted correctly.

FAQ

How can I scrape dynamic websites that load content via JavaScript?

For scraping dynamic content, you may need tools like Selenium or Puppeteer, which can interact with browser-rendered data.

Why is my web scraping script returning an empty result?

Ensure the URL is correct, check whether data is dynamically loaded (inspect page source vs network activity), and verify the HTML structure has not changed.

Is web scraping legal?

Web scraping legality depends on the website's terms of service and the laws of your jurisdiction. Always review and comply with the website's terms and robots.txt.


Official reference: Python documentation.