Scrape HTML Tables into Clean CSV and JSON with Python
pythonpandashtml-tablescsvdata-extraction

Scrape HTML Tables into Clean CSV and JSON with Python

sscraper.page Editorial Team
2026-12-06
6 min read

A practical Python checklist for extracting inconsistent HTML tables with pandas and Beautiful Soup, then validating CSV or JSON output.

Extracting an HTML table is easy when every row has the same cells and the page uses a clean header row. Real pages are less predictable. This guide provides a reusable Python workflow for turning ordinary and inconsistent HTML tables into validated CSV or JSON, using pandas for fast extraction and Beautiful Soup when you need precise control over headers, links, merged cells, or malformed markup.

Overview

Start by deciding whether the table is genuinely present in the downloaded HTML. If it is, pandas.read_html() is usually the quickest way to extract it. If the table contains nested links, irregular rows, missing headers, or complicated rowspan and colspan attributes, use Beautiful Soup to inspect and normalize the structure first.

Install the basic tools in an isolated environment:

python -m pip install pandas beautifulsoup4 lxml requests

A minimal pandas extraction looks like this:

import pandas as pd

url = "https://example.com/table-page"
tables = pd.read_html(url)

for index, table in enumerate(tables):
    print(index, table.shape)
    print(table.head())

The result is a list of DataFrames because one page can contain several tables. Do not assume that the first table is the one you want. Inspect dimensions, column names, and a few rows before exporting.

Once the correct DataFrame has been selected, export it explicitly:

table = tables[0]
table.to_csv("output.csv", index=False, encoding="utf-8-sig")
table.to_json("output.json", orient="records", force_ascii=False, indent=2)

The records JSON format is generally convenient because each row becomes an object. Preserve the original HTML or downloaded response alongside the output when the extraction needs to be audited or repeated.

Checklist by scenario

Standard table with a reliable header

  1. Download the page and confirm the expected table exists in the response.
  2. Use pd.read_html() and inspect every returned table.
  3. Rename columns to stable, application-friendly names.
  4. Strip whitespace and export only after checking row counts.
table = pd.read_html(html, match="Product")[0]
table.columns = [str(column).strip().lower().replace(" ", "_")
table = table.map(lambda value: value.strip() if isinstance(value, str) else value)

Depending on your pandas version, use an equivalent column-wise or element-wise cleaning operation if DataFrame.map is unavailable in your environment.

Missing or unreliable headers

Read the table without treating its first row as a header, then assign names yourself. This prevents a data row from silently becoming the schema.

table = pd.read_html(html, header=None)[0]
table.columns = ["name", "category", "value", "source"]

Before assigning names, verify the number of columns. If it varies between rows, normalize the HTML with Beautiful Soup or define a rule for padding and rejecting malformed rows.

pandas usually returns visible text, but a link URL may be important. Beautiful Soup lets you retain both values:

from bs4 import BeautifulSoup

soup = BeautifulSoup(html, "html.parser")
rows = []

for tr in soup.select("table.data tbody tr"):
    cells = tr.find_all(["th", "td"])
    if not cells:
        continue
    link = cells[0].find("a")
    rows.append({
        "name": cells[0].get_text(" ", strip=True),
        "url": link.get("href") if link else None,
        "value": cells[1].get_text(" ", strip=True) if len(cells) > 1 else None,
    })

Resolve relative links against the page URL before saving if the URLs will be used later. Also decide whether an absent link should become an empty string or a JSON null; use one convention consistently.

Multiple tables

Use a selector, table caption, distinctive text, or a shape check rather than a fixed index. A page redesign can add a navigation or summary table and shift every index.

tables = pd.read_html(html)
selected = next(
    table for table in tables
    if "product" in " ".join(map(str, table.columns)).lower()
)

Merged cells and irregular rows

rowspan and colspan can produce duplicated, blank, or multi-level columns. Inspect the parsed output before cleaning. For difficult tables, iterate through rows and expand spans according to the source layout, or use the rendered structure from a browser when the page depends on JavaScript. A browser-based workflow is covered in the Playwright guide for JavaScript-rendered websites.

Pagination

Identify whether pagination changes the URL, submits a form, calls an API, or loads more rows with JavaScript. Fetch each page, extract the same schema, concatenate the results, and remove duplicates using a stable key. Do not treat a visible page count as proof that every page was collected.

What to double-check

  • Source HTML: Save a response sample and confirm the table is not merely an empty client-side placeholder.
  • Encoding: Check accented characters, currency symbols, and non-Latin text before choosing an output encoding. UTF-8 is a sensible default; utf-8-sig can improve compatibility with some spreadsheet applications.
  • Headers: Confirm that every output column has a unique, meaningful name. Multi-row headers may need to be flattened deliberately.
  • Types: Dates, percentages, thousands separators, and values such as 00123 can be misinterpreted. Preserve identifiers as strings when leading zeros matter.
  • Missing values: Distinguish a blank cell, a source value such as “N/A,” and a genuinely unavailable field when that distinction affects downstream analysis.
  • Row counts: Compare extracted counts with the visible page, pagination controls, or an independent total where available.
  • Ethics and reliability: Follow the site's applicable access rules, use reasonable request rates, cache downloads, and prefer an official data endpoint when one is available. See HTML scraping versus API access for the decision process.

For repeat jobs, add schema checks such as required columns, allowed data types, and minimum row counts. Store a small fixture page and run the parser against it after code or dependency changes. The scraper testing and monitoring guide provides a practical structure for this.

Common mistakes

Choosing the first table without inspection is the most common failure. Pages often include layout, pricing, navigation, and data tables together. Inspect all candidates.

Assuming a browser view equals downloaded HTML causes empty results on JavaScript-rendered pages. Compare the response source with the DOM shown in developer tools, then use an appropriate rendering or endpoint strategy.

Cleaning before understanding the schema can erase useful distinctions. First preserve the raw values, then normalize whitespace, dates, numbers, and labels in separate steps.

Ignoring repeated headers creates apparent duplicate records when a long table repeats its header inside the body. Detect and remove rows whose values match the column labels.

Exporting without validation hides silent truncation and shifted columns. Reopen the CSV or JSON, inspect the first and last records, and test representative edge cases.

When to revisit

Revisit this workflow whenever the source changes its table layout, adds pagination, moves from server-rendered HTML to JavaScript, or changes labels and data types. It is also worth reviewing before a recurring collection cycle, such as a monthly report or seasonal planning process.

Use this final checklist before putting an extractor into regular use:

  1. Confirm whether an API or downloadable dataset is a better source.
  2. Save a representative HTML fixture, including an edge-case row.
  3. Choose pandas for regular tables and Beautiful Soup for controlled cell-level extraction.
  4. Define stable column names and explicit rules for missing values.
  5. Test links, merged cells, encoding, pagination, and duplicate handling.
  6. Export CSV for spreadsheet-oriented work and JSON for structured application input.
  7. Monitor row counts and schema changes so a layout change fails visibly rather than producing misleading data.

For broader cleanup after extraction, continue with the guide to cleaning and normalizing scraped data with Python.

Related Topics

#python#pandas#html-tables#csv#data-extraction
s

scraper.page Editorial Team

Developer Resources 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.