Scrape Website Data with Python: A Field-Mapping Template for Repeatable Exports
PythonBeautifulSoupCSVJSONdata pipelines

Scrape Website Data with Python: A Field-Mapping Template for Repeatable Exports

SScraper Studio Editorial Team
2026-11-28
7 min read

A reusable Python and BeautifulSoup workflow for mapping fields, handling pagination, validating records, and exporting website data to CSV or JSON.

To scrape website data reliably, define the fields before writing the parser. This field-mapping workflow shows how to discover pages, extract consistent values with Python and BeautifulSoup, handle missing data and pagination, normalize output, validate results, and export the same dataset to CSV or JSON whenever the source or workflow changes.

Overview

A web scraper is only as useful as the dataset it produces. A script that collects page text without a defined structure may work for a quick experiment, but repeatable exports require decisions about field names, data types, missing values, duplicate records, pagination, and output formats.

The central idea is to treat extraction as a small data pipeline:

  1. Discover: identify the index pages, detail pages, API responses, or embedded data that contain the records.
  2. Map: connect each target field to a stable HTML selector, attribute, JSON key, or fallback rule.
  3. Extract: request the page and collect raw values without losing the source URL.
  4. Normalize: clean whitespace, URLs, dates, numbers, and empty values into predictable forms.
  5. Validate: check required fields, record counts, duplicates, and suspicious output.
  6. Export: write CSV for spreadsheet workflows or JSON for applications and downstream pipelines.

Before collecting data, review the website’s published instructions, access requirements, and applicable terms. Limit request volume, identify your use case where appropriate, and avoid collecting personal or restricted information unless you have a valid reason and suitable controls.

The following example uses a catalog-style website with listing pages and detail pages. The selectors are placeholders: inspect the actual markup and replace them with selectors that match your source.

python -m venv .venv
source .venv/bin/activate
pip install requests beautifulsoup4

A simple field map might look like this:

FIELD_MAP = {
    "name": {"selector": "h1.product-name", "required": True},
    "summary": {"selector": "div.product-summary", "required": False},
    "price": {"selector": "span.price", "required": False},
    "category": {"selector": "a.breadcrumb-category", "required": False},
    "canonical_url": {"selector": "link[rel='canonical']", "attribute": "href", "required": False}
}

Keeping the mapping separate from the extraction logic makes the scraper easier to update. When a layout changes, you can usually revise selectors and fallback rules without rewriting the entire pipeline.

Checklist by scenario

Scenario 1: Extract records from a single page

Start with one representative URL. Confirm that the page contains the fields you want and that the HTML returned to Python includes them. A minimal extractor can use a helper that distinguishes text values from attributes:

import requests
from bs4 import BeautifulSoup


def get_value(soup, rule):
    node = soup.select_one(rule["selector"])
    if not node:
        return None
    if rule.get("attribute"):
        return node.get(rule["attribute"])
    return " ".join(node.get_text(" ", strip=True).split())


def fetch_record(url):
    response = requests.get(
        url,
        timeout=30,
        headers={"User-Agent": "DatasetResearch/1.0"}
    )
    response.raise_for_status()
    soup = BeautifulSoup(response.text, "html.parser")

    record = {"source_url": url}
    for field, rule in FIELD_MAP.items():
        record[field] = get_value(soup, rule)
    return record

Use a descriptive, honest user-agent rather than pretending to be a browser or another service. A timeout and status check prevent silent failures. Keep the source URL in every record so that an extracted value can be traced back to its origin.

Scenario 2: Crawl listing pages and detail pages

For a catalog, search result, or article index, separate discovery from extraction. First collect detail-page links, then process each detail page with the same field map.

from urllib.parse import urljoin


def discover_links(index_url):
    response = requests.get(index_url, timeout=30)
    response.raise_for_status()
    soup = BeautifulSoup(response.text, "html.parser")
    links = []
    for node in soup.select("a.product-card[href]"):
        links.append(urljoin(index_url, node["href"]))
    return list(dict.fromkeys(links))

records = []
for detail_url in discover_links("https://example.com/catalog"):
    records.append(fetch_record(detail_url))

Deduplicate links before fetching them. For larger jobs, add controlled delays, retries with limits, logging, and a cache. If the site uses JavaScript to render records, inspect the network requests first. A documented JSON endpoint may provide cleaner structured data than rendered HTML; if no suitable endpoint is available, a browser automation tool such as Playwright may be appropriate.

Scenario 3: Handle pagination

Pagination can use numbered links, a next-page link, cursor parameters, or an API response. Do not assume that incrementing a page number is safe. Follow the source’s actual pagination pattern and stop when there is no next page or when a configured maximum is reached.

def discover_all_links(start_url, max_pages=20):
    current_url = start_url
    seen_pages = set()
    all_links = []

    for _ in range(max_pages):
        if not current_url or current_url in seen_pages:
            break
        seen_pages.add(current_url)

        response = requests.get(current_url, timeout=30)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, "html.parser")

        for node in soup.select("a.product-card[href]"):
            all_links.append(urljoin(current_url, node["href"]))

        next_node = soup.select_one("a.next[href]")
        current_url = urljoin(current_url, next_node["href"]) if next_node else None

    return list(dict.fromkeys(all_links))

For API-based collection, record the request parameters and response metadata separately from the normalized records. This makes it easier to diagnose a partial export or a changed cursor format. See the guide to handling API pagination with a web scraper for a deeper pagination checklist.

Scenario 4: Export to CSV and JSON

Use consistent column order and explicit handling for missing values. CSV is convenient for spreadsheets, while JSON preserves nested structure and field types more naturally.

import csv
import json

fields = ["source_url", "name", "summary", "price", "category", "canonical_url"]

with open("records.csv", "w", newline="", encoding="utf-8") as file:
    writer = csv.DictWriter(file, fieldnames=fields, extrasaction="ignore")
    writer.writeheader()
    writer.writerows(records)

with open("records.json", "w", encoding="utf-8") as file:
    json.dump(records, file, ensure_ascii=False, indent=2)

When records may be numerous, JSON Lines is often easier to append and process incrementally than one large JSON array. Choose the format based on the next system in the pipeline, not only on what is easiest to inspect. The comparison of CSV, JSON, JSONL, and Parquet can help with that decision.

What to double-check

  • Field definitions: Write down whether a field is text, a URL, a number, a date, a list, or an optional value.
  • Selector coverage: Test several page variants, including records with missing images, unusually long titles, alternate templates, or empty descriptions.
  • Normalization: Collapse repeated whitespace, resolve relative URLs, standardize casing only where appropriate, and preserve meaningful punctuation.
  • Numbers and dates: Store raw values when parsing is uncertain. If you convert currencies, units, or localized dates, document the rule and retain the original value when useful.
  • Canonical identity: Choose a stable record key, such as a canonical URL or source identifier. Normalize and deduplicate URLs before counting records; the URL normalization guide covers common edge cases.
  • Required fields: Fail loudly or quarantine records missing essential fields instead of exporting incomplete rows as if they were valid.
  • Validation counts: Compare discovered links, fetched pages, successful parses, skipped pages, and exported records. Large unexplained differences deserve investigation.
  • Structured data: Check JSON-LD, Open Graph, or other embedded metadata when visible HTML is incomplete. These sources may complement, not replace, visible-page extraction; see the guide to extracting structured page data.

A lightweight validation pass can catch obvious problems:

required = ["source_url", "name"]
valid = []
invalid = []

for record in records:
    missing = [field for field in required if not record.get(field)]
    (invalid if missing else valid).append(record)

print(f"valid={len(valid)} invalid={len(invalid)}")
assert valid, "No valid records were exported"

Common mistakes

Writing selectors against one page only. A selector that works for the first result may fail on sponsored, archived, sold-out, or differently categorized pages. Test a sample across the full source.

Mixing discovery and parsing logic. When one function finds links, extracts fields, writes files, and handles retries, changes become difficult to isolate. Keep those stages separate.

Using empty strings for every failure. An empty string can mean “the field is absent,” “the selector broke,” or “the request failed.” Use None, an error field, or a rejected-record file so those cases remain distinguishable.

Ignoring duplicates. The same item may appear in multiple categories, tracking URLs, or pagination views. Normalize URLs and define the record identity before export.

Assuming a successful HTTP response means successful extraction. A page can return a normal status while showing a challenge, login page, error template, or incomplete shell. Log a sample title, content length, and selected-field count for each batch.

Overlooking dynamic content. If the HTML response does not contain the data, BeautifulSoup cannot create it. Inspect embedded JSON or network requests before introducing browser automation, and use browser tooling only when the source requires it.

For failures involving empty results, timeouts, or blocked requests, use a separate diagnostic process rather than weakening validation. The web scraper debugging checklist provides a practical sequence.

When to revisit

Revisit this workflow before each recurring export, seasonal planning cycle, or major change to the source website. The most useful update triggers are a redesigned page, a new pagination method, changed field labels, a switch from server-rendered HTML to client-rendered content, or a dependency update that changes parser behavior.

Keep a small test fixture containing representative HTML responses and expected records. Run it whenever you change selectors, normalization rules, or package versions. Also compare the new export with the previous one: record counts, missing-field rates, duplicate rates, and a sample of normalized values can reveal a quiet break that a successful script run would not show.

Before running the next job, use this short checklist:

  1. Confirm the target pages and access assumptions.
  2. Inspect one current page and update the field map if needed.
  3. Test discovery, pagination, and deduplication independently.
  4. Run a small sample before the full export.
  5. Review validation counts and rejected records.
  6. Save the run date, code version, field map, and output format with the dataset.

Once those checks pass, the same Python web scraping template can support a dependable CSV, JSON, or JSONL export without turning every new source into a one-off script.

Related Topics

#Python#BeautifulSoup#CSV#JSON#data pipelines
S

Scraper Studio Editorial Team

Technical Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.