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:bashpip install beautifulsoup4 lxml requests
Steps to Set Up the Script
This section helps you create a Python script for web scraping.
steps
Create a Python script (
scraper.py): Open your text editor or IDE and create a new Python file calledscraper.py.Import necessary libraries: At the beginning of the file, import the required Python modules:
pythonfrom bs4 import BeautifulSoup import requests import csvFetch an HTML file or use a local file for testing:
- For live websites: Use the
requestslibrary to fetch the website's HTML content. - For local HTML files: Open and read the file into your script.
- For live websites: Use the
Load HTML content into BeautifulSoup: To parse and work with the HTML:
pythonwith open("sample.html", "r") as html_file: content = html_file.read() soup = BeautifulSoup(content, 'lxml')Identify the elements to scrape:
- Use
soup.find()orsoup.find_all()to locate elements by HTML tag names or CSS class names. - For example:
pythontitles = soup.find_all('h5', class_='course-title')- Use
Extract data: Extract the text or attributes from the HTML elements:
pythonfor 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
Structure your data: Create a list of lists where each sublist represents a row of data:
pythondata = [['Python Basics', '$20'], ['Django Web Development', '$25']]Write the data to CSV: Use Python's built-in
csvmodule:pythonimport csv with open('courses.csv', 'w', newline='') as file: writer = csv.writer(file) writer.writerow(['Title', 'Price']) # Header row writer.writerows(data)Verify CSV output: Check the saved
courses.csvfile 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.