Learn how to scrape a website with Python using Requests and Beautiful Soup, then extend the workflow with pagination, retries, validation, and structured output. This reusable checklist helps you build small, maintainable scrapers without confusing missing data, changing HTML, or blocked requests with successful results.
Overview
A Python web scraper usually has four stages: request a page, parse its HTML, extract the fields you need, and save the results. requests handles the HTTP request, while BeautifulSoup provides a practical HTML parser for locating elements with CSS selectors or other search methods.
Before writing code, confirm that the data is available in the HTML returned by the server. Open the page source or inspect a response saved locally. If the content only appears after JavaScript runs, a simple Requests and Beautiful Soup workflow may not be sufficient. Look for an available API or data endpoint first; where browser automation is necessary, use it deliberately and keep the extraction logic separate from the browser-control code.
Also define the scope of the job. Identify the pages to collect, the fields required, the expected output format, and a stopping condition. Review the site's published instructions and applicable requirements before running a scraper, and use conservative request rates. A technically correct script can still be an unreliable workflow if it has no timeout, no duplicate handling, and no way to detect an error page.
A minimal Requests and Beautiful Soup example
from pathlib import Path
import csv
import requests
from bs4 import BeautifulSoup
url = 'https://example.com/products'
headers = {'User-Agent': 'ExampleResearchBot/1.0'}
response = requests.get(url, headers=headers, timeout=20)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
rows = []
for card in soup.select('.product-card'):
name_node = card.select_one('.product-name')
price_node = card.select_one('.product-price')
rows.append({
'name': name_node.get_text(' ', strip=True) if name_node else None,
'price': price_node.get_text(' ', strip=True) if price_node else None,
'url': card.select_one('a')['href'] if card.select_one('a') else None,
})
with Path('products.csv').open('w', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=['name', 'price', 'url'])
writer.writeheader()
writer.writerows(rows)
The selectors in this example are placeholders. Replace them after inspecting the target markup, and treat every extracted field as optional until you have verified that the element exists. The conditional checks prevent a missing element from terminating the whole run.
Checklist by scenario
For a single page
- Use a clear URL and a reasonable timeout.
- Check the response status before parsing.
- Parse the response using the intended HTML parser.
- Extract only the fields needed for the task.
- Save the raw HTML or a small sample when debugging.
For a one-off extraction, a short script may be enough. Even then, print the number of records found and inspect several output rows. An empty list can mean that the page contains no matching records, but it can also indicate a selector error, a consent page, a block page, or JavaScript-rendered content.
For numbered pagination
Some sites expose pages through a query parameter such as ?page=2 or through a path segment. Begin with a known page, extract its records, and stop when the page has no new records or when the site's pagination control indicates that there is no next page.
from urllib.parse import urljoin
base_url = 'https://example.com/products'
seen = set()
all_rows = []
for page_number in range(1, 51):
response = requests.get(
base_url,
params={'page': page_number},
headers=headers,
timeout=20,
)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
cards = soup.select('.product-card')
if not cards:
break
added = 0
for card in cards:
link = card.select_one('a')
href = urljoin(response.url, link.get('href')) if link else None
if href in seen:
continue
seen.add(href)
all_rows.append({
'url': href,
'name': card.get_text(' ', strip=True),
})
added += 1
if added == 0:
break
A fixed upper bound is a useful safety control, not a substitute for understanding the site's pagination. For next links, parse the link and continue until it is absent. For cursor-based pagination or infinite scroll, inspect the page's network requests and consider whether an official or documented endpoint is a better fit. The guide to pagination patterns and deduplication covers these variations in more detail.
For unreliable responses
Use a session when you need shared headers or cookies, add timeouts to every request, and handle temporary failures separately from permanent failures. A retry policy should have a limited number of attempts and increasing delays. Do not retry an invalid selector or a consistently forbidden response as if it were a network problem. For a fuller implementation, see rate limits, retries, backoff, timeouts, and polite crawling.
For JavaScript-rendered pages
Compare the HTML from requests with what appears in a normal browser. If the records are absent from the response, identify the data request that supplies them, provided you are authorized to access it. An API response is often easier to validate than rendered markup. If browser automation is required, wait for a specific page condition rather than relying only on a fixed sleep, and keep the number of pages and interactions bounded.
What to double-check
- Selectors: Prefer stable attributes and structural relationships over long, generated class-name chains. Test selectors against several records, not just the first match.
- URLs: Convert relative links with
urljoin, remove duplicates deliberately, and decide whether tracking parameters should be retained. - Missing values: Return
Noneor an empty value consistently. Do not silently shift columns because one card lacks a field. - Text normalization: Use
get_text(' ', strip=True), then apply field-specific cleanup for whitespace, currencies, dates, or units. - Character encoding: Preserve Unicode and choose an explicit encoding when writing CSV or JSON.
- Pagination: Check for repeated pages, loops, skipped cursors, and a final page that returns an error template with a successful HTTP status.
- Validation: Record page counts, row counts, duplicate counts, and a few representative values. These basic metrics make silent failures visible.
- Storage: Keep raw inputs or snapshots for a small test set. This makes it possible to distinguish a website redesign from a code regression.
When the target contains tables, compare Beautiful Soup with a table-oriented approach before adding complicated selectors. The overview of HTML table scraping in Python explains where pandas, Beautiful Soup, lxml, and Selectolax can fit.
Common mistakes
- Skipping the status check. Parsing an error page as if it were the target page produces plausible-looking but incorrect output. Call
raise_for_status()and inspect the response when results are unexpected. - Using one fragile selector. A selector that depends on a specific position or generated class can fail after a minor redesign. Add fallbacks only when they are meaningful, and test that fallbacks do not capture unrelated text.
- Assuming an empty result means “finished.” It may indicate a block, login page, changed markup, or a JavaScript dependency. Log the URL and a short response preview before stopping.
- Ignoring duplicates. Pagination links, filters, and canonical URLs can expose the same record more than once. Choose a stable record key and deduplicate before export.
- Running without limits. Unbounded loops and parallel requests make failures harder to diagnose and increase load. Set page, record, time, and retry limits.
- Testing only against live pages. Live pages change. Save representative HTML fixtures and add regression checks so selector changes are detected before a scheduled run.
For a maintainable project, separate fetching, parsing, validation, and export into functions. This lets you test parsing with stored HTML without making network requests. The guide to HTML fixtures, snapshots, and CI checks provides a practical testing workflow.
When to revisit
Revisit this scraper before a new scheduled collection cycle, especially before seasonal planning or any period when the volume or importance of the output changes. Confirm that the page structure, pagination method, authentication state, and requested fields are still the same. Run a small sample first, compare row counts with an expected range, and inspect both successful and empty responses.
Update the workflow when the site introduces a redesign, a new consent flow, a login requirement, an API, or client-side rendering. Also revisit it when you change Python dependencies, move from a local script to a scheduled job, or see a sudden drop in records. If authentication is involved, do not hard-code credentials or tokens; review the session design and access rules described in authenticated scraping patterns.
A practical final checklist is: verify permission and scope, test one page, confirm selectors, add timeouts, handle missing fields, bound pagination, deduplicate records, validate counts, save structured output, and monitor the next run. If the scraper returns empty pages or suspiciously consistent errors, stop treating the output as complete and investigate the response before continuing.