Lesson 44 of 59Libraries every Python developer knows
Web Scraping Responsibly
Scrape pages politely with httpx, BeautifulSoup and Playwright, handle pagination, and store results, after checking whether you should.
Sometimes the data you need is only on a web page: competitor prices, a public list of events, job postings, a government table with no download link. Web scraping means fetching pages with code and pulling structured data out of the HTML. It is a useful skill and a common take-home task, but it comes with responsibilities that a careless scraper ignores: respect the site's rules, do not hammer its servers, and do not collect what you have no right to. This lesson covers when scraping is OK, the tools for static and JavaScript-heavy pages, and how to build a scraper that is polite and easy to maintain.
Before you write a line: should you scrape?
Ask these questions in order:
- Is there an API or a data export? An official API is faster, more stable and clearly permitted. Many sites also offer CSV downloads, RSS feeds or sitemaps. Scraping HTML is the last resort, because the page layout can change any day and break your code.
- What do the terms of service say? Many sites forbid automated access. Breaking terms can get your IP blocked or create legal risk. This is not legal advice; when it matters, ask someone who knows.
- What does
robots.txtsay? Sites publish crawling rules at/robots.txt. They are a convention, not a lock, but respecting them is the baseline of good behaviour. - Is it personal data? Collecting names, emails or profiles brings in privacy law such as GDPR, wherever the data is public or not. Avoid it unless you have a clear lawful reason.
Python's standard library can read robots.txt rules for you:
Press Run (⌘ Enter) to see what happens.In a real scraper you call rules.set_url("https://shop.example.com/robots.txt") and rules.read() once at startup instead of parsing a string.
Static pages: httpx and BeautifulSoup
If the data is in the HTML the server sends (check with your browser's "View Page Source", not the inspector, which shows the page after JavaScript ran), you only need an HTTP client and a parser. Install with uv add httpx beautifulsoup4.
import httpx
from bs4 import BeautifulSoup
client = httpx.Client(
headers={"User-Agent": "razorcode-price-bot/1.0 (+mailto:data@example.com)"},
timeout=10.0,
follow_redirects=True,
)
response = client.get("https://shop.example.com/products?page=1")
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
for card in soup.select("article.product"):
name = card.select_one("h2").get_text(strip=True)
price = card.select_one(".price").get_text(strip=True)
link = card.select_one("a")["href"]
print(name, price, link)The client habits from the requests and httpx lesson apply here: one shared client, a timeout on every call, and raise_for_status(). The User-Agent names your bot and gives a contact, so a site owner can reach you instead of simply blocking you.
Selecting elements
CSS selectors are the same patterns you use in stylesheets, and they are the clearest way to find things:
| Selector | Matches |
|---|---|
h2 | Every <h2> |
.price | Elements with class="price" |
#results | The element with id="results" |
article.product | <article> elements with class product |
ul.items > li | <li> that are direct children of ul.items |
a[href^="/products/"] | Links whose href starts with /products/ |
[data-sku] | Elements with a data-sku attribute |
soup.select(selector) returns a list of every match, and soup.select_one(selector) returns the first match or None. On an element, .get_text(strip=True) gives its text, el["href"] reads an attribute and raises if it is missing, and el.get("href") returns None instead.
Prefer stable hooks: ids, data-* attributes, and semantic class names like product or price. Avoid long paths like div > div:nth-child(3) > span, which break as soon as a designer adds a wrapper. And plan for missing pieces: a product without a price should be logged and skipped, not crash the run.
What does this print?
html = '<ul><li class="item">A</li><li>B</li><li class="item">C</li></ul>'
soup = BeautifulSoup(html, "html.parser")
print(len(soup.select("li.item")))Match each CSS selector to what it finds.
Pagination and polite delays
Most listings span many pages. The cleanest approach is to follow the page's own "next" link until there is none, with a hard cap so a bug cannot crawl forever. Wait between requests: a scraper that fires requests as fast as Python allows is indistinguishable from an attack.
import time
from urllib.parse import urljoin
BASE = "https://shop.example.com"
MAX_PAGES = 50
DELAY_SECONDS = 2.0 # honour Crawl-delay if robots.txt sets one
def crawl(client: httpx.Client) -> list[dict]:
results: list[dict] = []
url: str | None = f"{BASE}/products?page=1"
pages = 0
while url and pages < MAX_PAGES:
if not rules.can_fetch(USER_AGENT, url):
break
response = client.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.text, "html.parser")
for card in soup.select("article.product"):
if (price := card.select_one(".price")) is None:
continue
results.append({
"url": urljoin(BASE, card.select_one("a")["href"]), # relative links made absolute
"name": card.select_one("h2").get_text(strip=True),
"price": parse_price(price.get_text(strip=True)),
})
next_link = soup.select_one("a[rel=next]")
url = urljoin(BASE, next_link["href"]) if next_link else None
pages += 1
time.sleep(DELAY_SECONDS)
return resultsOnce at startup: which paths are allowed, and is there a crawl delay?
More good manners: run during off-peak hours for big jobs, cache pages you already fetched so a re-run of your parser does not re-download them, and stop entirely if you keep getting 403 or 429.
JavaScript-rendered pages: Playwright
Some pages arrive as an almost empty HTML shell and build their content with JavaScript. httpx only sees the shell. You have two options.
First, look for the data source. Open the browser's developer tools, go to the Network tab, filter by Fetch/XHR, and reload. The page often loads its data as JSON from an internal endpoint. Calling that with httpx is simpler and lighter than running a browser, though the same rules about terms and permission still apply.
Otherwise, drive a real browser. Playwright for Python controls Chromium, Firefox or WebKit. Install it with uv add playwright, then download a browser with uv run playwright install chromium.
from playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch() # headless by default
page = browser.new_page(user_agent="razorcode-price-bot/1.0 (+mailto:data@example.com)")
page.goto("https://spa.example.com/events")
page.wait_for_selector(".event-card") # wait until JavaScript has rendered the list
names = page.locator(".event-card h3").all_inner_texts()
html = page.content() # or hand the rendered HTML to BeautifulSoup
browser.close()Playwright also has an async API (playwright.async_api) for running several pages concurrently. A browser costs far more CPU and memory than an HTTP request, so use it only for pages that need it. It is also the tool behind end-to-end tests, so the skill carries over.
httpx.get(url).text returns HTML with an empty <div id="root"></div>, but the browser shows a full list. What should you try first?Storing results
Decide what "a row" is and give each one a stable key, usually the canonical URL or the site's own id. Then:
- CSV or JSON Lines (one JSON object per line) for one-off jobs. JSON Lines appends cleanly, so a crash halfway keeps everything collected so far.
- SQLite or Postgres for scrapers that run repeatedly. An upsert on the key (
INSERT ... ON CONFLICT (url) DO UPDATE) makes re-runs safe: no duplicates, and changed prices update in place. - Keep a timestamp (
scraped_at) on every row, and consider keeping the raw HTML of a sample of pages. When the layout changes and your selectors return nothing, you can see exactly what changed.
Validate as you store. A Pydantic model for each row turns "the price came back as an empty string" into a clear error instead of bad data downstream. For scraping at real scale, the Scrapy framework handles scheduling, throttling and pipelines for you, but for most jobs httpx plus BeautifulSoup is enough.
When the site changes
Scrapers break. Not if, when. A class gets renamed, a layout moves, a cookie banner appears. Three habits keep that from turning into silent bad data:
- Test the parser against saved HTML. Save a real page into
tests/fixtures/and write a pytest test that parses it and checks the expected rows. Parsing logic stays in a pure function (parse_products(html) -> list[Product]), separate from fetching, so it is fast to test. - Watch the numbers. Log how many items each run found. Yesterday 2,400 products, today 0 means your selectors broke, not that the shop closed. Alert on that.
- Fail loudly on structure, softly on records. If the main container is missing, stop the run with an error. If one product is malformed, log it and carry on.
- web scraping
- Fetching web pages with code and extracting structured data from their HTML.
- robots.txt
- A file at a site's root listing which paths automated clients may crawl, and sometimes how often.
- CSS selector
- A pattern like
article.product h2that finds elements by tag, class, id or attribute. - BeautifulSoup
- A Python library that parses HTML and lets you search it with selectors and read text and attributes.
- Playwright
- A library that drives a real browser, used for JavaScript-rendered pages and end-to-end tests.
- pagination
- Data split across numbered pages; a scraper follows next links until there are none.
- upsert
- Insert a row, or update it if one with the same key exists, so re-runs do not create duplicates.