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.
- 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:
- 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! - Check
robots.txtand Terms of Service: Inspecthttps://example.com/robots.txt(or use Python'surllib.robotparser) and never scrape authenticated accounts, paywalled content, or personal user data without explicit permission. - Send an honest
User-Agentand timeout: Identify your script clearly (e.g.,"CatalogResearchBot/1.0 (+contact@example.com)") and always settimeout=10so a hung server doesn't freeze your pipeline forever. - 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! - Throttle and handle rate limits (
429): Pausetime.sleep(1.5)between requests and back off exponentially if you receive HTTP429 Too Many Requestsor503.
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)
<div class="course">
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:
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 HTTP404or500instead 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, orNoneif missing.if title_el else "": Crucial defensive guard! On real websites, one product might lack a price badge or discount tag—calling.get_text()onNonecrashes the whole run withAttributeError.urljoin(BASE_URL, link_el["href"]): Safely combines base domain + relative path ("/courses/1"→"https://example.com/courses/1").
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:
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
In BeautifulSoup, what is the difference between soup.select('a.nav') and soup.select_one('a.nav')?
Why should scrapers include delays (time.sleep) between page fetches and respect robots.txt?
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?