5. Web Scraping & Workflow Automation

Extracting Structured Data from HTML (BeautifulSoup & html.parser)

Scrape public web pages responsibly when no API exists: check robots.txt and rate limits, parse DOM trees with BeautifulSoup CSS selectors, and clean extracted text into structured records.

5 min readUpdated 2026-11-30
In This Lesson
  • Follow ethical scraping practices (check for public APIs first, respect robots.txt, throttle requests)
  • Extract structured records from HTML markup using BeautifulSoup CSS selectors (.select)
  • Parse HTML cleanly using Python's built-in html.parser when zero external libraries are needed

Suppose you need weekly pricing snapshots from a public hardware catalog or government open-data portal, and there is no "Download CSV" button anywhere on the site. Web scraping turns raw HTML pages into structured Python records you can feed straight into Pandas—provided you collect data ethically, legally, and gently.

1. Golden Rules of Ethical & Reliable Scraping

Before writing a single HTTP request, walk through this 5-point checklist:

  1. Hunt for a hidden JSON API first: Open DevTools → Network → Fetch/XHR and reload the page. Many modern sites actually pull clean JSON from /api/products.json—which is 10x cleaner and lighter than scraping HTML!
  2. Check robots.txt and Terms of Service: Inspect https://example.com/robots.txt (or use Python's urllib.robotparser) and never scrape authenticated accounts, paywalled content, or personal user data without explicit permission.
  3. Send an honest User-Agent and timeout: Identify your script clearly (e.g., "CatalogResearchBot/1.0 (+contact@example.com)") and always set timeout=10 so a hung server doesn't freeze your pipeline forever.
  4. Cache HTML locally while developing: Fetch each page once, save it to cache/page_1.html, and test your CSS selectors against the local file instead of hitting the live site 40 times in a loop!
  5. Throttle and handle rate limits (429): Pause time.sleep(1.5) between requests and back off exponentially if you receive HTTP 429 Too Many Requests or 503.
Static HTML vs JavaScript-Rendered SPAs

httpx + BeautifulSoup reads the raw HTML sent by the server. If soup.select(...) returns [] even though you see items in Chrome, the page is likely rendered client-side by JavaScript—check the Network tab for the underlying JSON API before reaching for a headless browser like Playwright.

2. Parsing HTML with BeautifulSoup (bs4)

Parsing an HTML DOM Tree with CSS Selectors
<section class="catalog">

<div class="course">

<h3>Python</h3><span.hours>16h</span>

BeautifulSoup .select('div.course') walks each parent card node and safely extracts child tags via .select_one().

Locally, pair httpx with BeautifulSoup (pip install beautifulsoup4 httpx) and target elements cleanly with CSS selectors:

python
from urllib.parse import urljoin
import httpx
from bs4 import BeautifulSoup

BASE_URL = "https://example.com/courses"
resp = httpx.get(BASE_URL, headers={"User-Agent": "AcademyAnalyzer/1.0"}, timeout=10.0)
resp.raise_for_status()

soup = BeautifulSoup(resp.text, "html.parser")
cards = []

for card in soup.select("article.course-card"):
    title_el = card.select_one("h2.title")
    price_el = card.select_one("span.price")
    link_el = card.select_one("a[href]")

    # Always resolve relative links like "/courses/python" into full URLs!
    href = urljoin(BASE_URL, link_el["href"]) if link_el else ""

    cards.append({
        "title": title_el.get_text(strip=True) if title_el else "",
        "price": price_el.get_text(strip=True) if price_el else "0",
        "url": href,
    })

Line-by-Line Walkthrough & Defensive Guards

  • resp.raise_for_status(): Fails fast on HTTP 404 or 500 instead of silently parsing an error page into empty records.
  • soup.select("article.course-card"): Returns a list of all matching <article class="course-card"> nodes (empty list [] if none match).
  • card.select_one("h2.title"): Returns the first matching child tag, or None if missing.
  • if title_el else "": Crucial defensive guard! On real websites, one product might lack a price badge or discount tag—calling .get_text() on None crashes the whole run with AttributeError.
  • urljoin(BASE_URL, link_el["href"]): Safely combines base domain + relative path ("/courses/1" → "https://example.com/courses/1").
Don't Fragile-Chain Deep Selectors

Avoid brittle auto-generated selectors like div > div:nth-child(3) > span:nth-child(2). One tiny CSS redesign breaks them overnight! Prefer semantic tags, class names, or data-* attributes like div.course[data-level].

3. Built-In html.parser.HTMLParser (Zero Dependencies)

When shipping lightweight scripts with zero third-party packages (or running inside restricted sandboxes), Python's standard library includes html.parser.HTMLParser. Unlike BeautifulSoup's DOM tree, HTMLParser streams tags as events (handle_starttag → handle_data → handle_endtag) using tiny constant memory.

Try It Yourself in the Playground

Parse structured course cards—including attributes, nested text, and link URLs—using Python's built-in HTMLParser right inside the browser:

Python 3Try It Live: Extracting Structured Records from HTML
Output

Click “Run Code” to execute this snippet right in your browser.

Mini-Challenge: Why should you save downloaded HTML pages locally to disk while developing and debugging your BeautifulSoup selectors?

Quick Checkpoints

Check Your Understanding

In BeautifulSoup, what is the difference between soup.select('a.nav') and soup.select_one('a.nav')?

Check Your Understanding

Why should scrapers include delays (time.sleep) between page fetches and respect robots.txt?

Check Your Understanding

You run card.select_one('span.discount').get_text(strip=True) across 100 product cards, and it crashes with AttributeError: 'NoneType' object has no attribute 'get_text' on card #14. Why?