Build a web scraper with Python and BeautifulSoup by fetching a web page, parsing its HTML, selecting the data you need, and saving it in a clean format. BeautifulSoup is popular because it turns messy HTML into something you can search with simple Python code, and it is built for pulling data from HTML and XML files [source: Beautiful Soup].
TLDR: A basic scraper uses requests to download a page and BeautifulSoup to extract text, links, prices, titles, or tables. For example, a small store could check 100 competitor product pages each morning and flag any price drop over 10%. The result can be saved to CSV, JSON, or a database. Start small, test often, and scrape politely.
What You Need First
You do not need a huge setup. A simple Python project is enough. Create a folder, open your terminal, and install the two main packages:
pip install requests beautifulsoup4
requests gets the page. BeautifulSoup reads the page. That split keeps the code easy to understand.
Here is the smallest useful scraper:
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
title = soup.find("h1")
print(title.get_text(strip=True))
This asks the site for its HTML, parses it, finds the first <h1> tag, and prints the clean text. Not glamorous. Very useful.
Step 1: Inspect the Page
Before writing code, open the target page in your browser. Right click the item you want and choose Inspect. Look for the tag, class, or ID around the data.
For example, a product name might look like this:
<h2 class="product-title">Wireless Mouse</h2>
Then your scraper can target it like this:
name = soup.find("h2", class_="product-title")
print(name.get_text(strip=True))
The annoying part is that one missing CSS class can turn a 2 second scrape into a 20 minute debugging session. Websites change. Your scraper should be easy to update.
Step 2: Extract Multiple Items
Most scrapers need more than one result. Use find_all() to grab a list of matching elements.
products = soup.find_all("div", class_="product")
for product in products:
name = product.find("h2", class_="product-title")
price = product.find("span", class_="price")
print({
"name": name.get_text(strip=True) if name else None,
"price": price.get_text(strip=True) if price else None
})
Notice the if name else None checks. They prevent your script from crashing when a product card is missing a field. This happens more often than anyone wants.
Step 3: Save the Results
Printing data is fine for testing. Real projects need storage. CSV is simple and works with Excel, Google Sheets, and many reporting tools.
import csv
data = [
{"name": "Wireless Mouse", "price": "$19.99"},
{"name": "USB Keyboard", "price": "$29.99"}
]
with open("products.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["name", "price"])
writer.writeheader()
writer.writerows(data)
Once saved, you can compare prices over time, track stock changes, or build a small report. A daily scrape of 200 items can become a useful trend file after only two weeks.
Step 4: Add Headers and Timeouts
Some sites block plain scripts because they look robotic. Add a user agent and a timeout. This also stops your script from hanging forever when a server is slow.
headers = {
"User-Agent": "Mozilla/5.0"
}
response = requests.get(url, headers=headers, timeout=10)
Expect to waste time on small network issues. A page may load fine in your browser, then fail from your script because of cookies, redirects, or JavaScript.
Step 5: Be Polite and Legal
Scraping is not a free pass to hammer a site. Check the site’s terms. Read its robots.txt file. Add delays between requests. The robots.txt standard explains how sites can tell crawlers which paths are allowed or blocked [source: RFC Editor].
- Do not send hundreds of requests per second.
- Do cache pages during testing.
- Do identify your scraper when needed.
- Do not scrape private data or bypass logins without permission.
Common Problems
- Empty results: The content may be loaded by JavaScript after the page opens.
- Blocked requests: Try headers, slower request rates, or an approved API.
- Broken selectors: The site changed its HTML.
- Encoding issues: Save files with
encoding="utf-8".
If the data appears only after clicking buttons or scrolling, BeautifulSoup alone may not be enough. You may need tools like Selenium or Playwright. Use them only when needed, because they are heavier and slower.
A Simple Final Scraper
import requests
from bs4 import BeautifulSoup
import csv
import time
url = "https://example.com/products"
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers, timeout=10)
soup = BeautifulSoup(response.text, "html.parser")
rows = []
for item in soup.find_all("div", class_="product"):
name = item.find("h2", class_="product-title")
price = item.find("span", class_="price")
rows.append({
"name": name.get_text(strip=True) if name else "",
"price": price.get_text(strip=True) if price else ""
})
time.sleep(1)
with open("products.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.DictWriter(file, fieldnames=["name", "price"])
writer.writeheader()
writer.writerows(rows)
A good scraper is boring in the best way. It fetches pages, handles missing data, waits between requests, and saves clean output. Start with one page. Then add more fields. Then add more pages. Keep it simple, and it will be much easier to fix when the website changes.