Web scraping
Web scraping with Python: a working guide
Most Python scrapers are built from the same handful of pieces: a session, a parser, a loop over pages, a retry policy and somewhere to put the data. This guide walks through each one with code you can keep, and shows where a CAPTCHA fits when a site asks for one.
What a working scraper needs
A scraper that runs once on your laptop and a scraper that runs every night for a year are different programs. The second one has to cope with slow responses, temporary errors, layout changes, pages that move, and the occasional challenge page. The good news is that Python's ecosystem covers all of that with a small toolset:
- requests for HTTP, with a
Sessionthat keeps cookies and connections; - Beautiful Soup (with the
lxmlparser if you can install it) for reading HTML; - urllib3's Retry, which requests already depends on, for automatic retries;
- the standard library's
csv,jsonandurllib.robotparserfor output and good manners.
Everything here works on Python 3.10 or newer. For pages that build their content with JavaScript you will eventually want a browser, but start with plain HTTP: it is faster, cheaper and easier to debug. Our note on static or dynamic pages helps you tell which kind you face.
Start with the network, not the parser
Before writing any parsing code, open the target page in your browser with DevTools on the Network panel and reload. Two things are worth noticing. First, whether the data is in the HTML document itself or arrives later from a JSON request. If it is JSON, scrape that endpoint instead of the HTML; it is cleaner and changes less often, an approach covered in hidden API scraping. Second, which headers and cookies the browser sends. You do not need to copy all of them, but a realistic User-Agent and Accept-Language avoid many needless blocks.
A session that behaves
A requests.Session reuses TCP connections, keeps cookies between requests, and lets you set defaults once. Mount an HTTPAdapter with a Retry policy and transient errors are retried automatically with exponential backoff.
import requests
from requests.adapters import HTTPAdapter as PoolAdapter
from urllib3.util import Retry
def make_session() -> requests.Session:
retry_policy = Retry(
total=4, backoff_factor=1.5,
status_forcelist=(429, 500, 502, 503, 504),
allowed_methods=frozenset({"GET", "HEAD"}),
respect_retry_after_header=True,
)
s = requests.Session()
s.mount("https://", PoolAdapter(max_retries=retry_policy, pool_maxsize=8))
s.headers.update({
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) research-crawler/1.0 (+mailto:ops@example.org)",
"Accept-Language": "en-US,en;q=0.5",
})
return s
A few choices here are deliberate. Only idempotent methods are retried, so a form post is never sent twice by accident. The Retry-After header is honored, which matters for 429 responses. The User-Agent names the crawler and gives a contact, which many site operators appreciate; if you scrape as a browser instead, keep the string current and consistent. Always pass a timeout to every request; requests has no default and a stalled connection will otherwise hang forever.
Parse with selectors you can read
CSS selectors are usually the clearest way to point at data. Write them against stable attributes (ids, data- attributes, semantic class names) rather than long chains of generic div elements, so a small layout change does not break everything.
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup as Soup
def parse_listing(html: str, base: str) -> tuple[list[dict], str | None]:
doc = Soup(html, "lxml")
rows = []
for card in doc.select("article[data-product-id]"):
title = card.select_one("h2")
price = card.select_one("[itemprop=price], .price")
rows.append({
"id": card["data-product-id"],
"title": title.get_text(strip=True) if title else None,
"price": price.get_text(strip=True) if price else None,
})
nxt = doc.select_one("a[rel=next]")
return rows, (urljoin(base, nxt["href"]) if nxt else None)
Notice the guards around optional elements: real pages have products without prices and titles wrapped in odd markup. Returning None for a missing field and counting how often it happens is far better than crashing at row 3,000. If you prefer XPath, lxml.html supports it directly; Beautiful Soup does not, as our note on XPath in Beautiful Soup explains.
Walk the pages politely
Pagination is a loop: fetch a page, parse rows, find the next link, repeat. Add three safety features. A delay between requests so you do not load the site; a maximum page count so a broken "next" link cannot loop forever; and a check of robots.txt before you start.
import csv
import time
import random
import urllib.robotparser as robotparser
def crawl(start: str, out_path: str, max_pages: int = 200) -> None:
robots = robotparser.RobotFileParser(urljoin(start, "/robots.txt"))
robots.read()
sess, url, seen = make_session(), start, 0
with open(out_path, "w", newline="", encoding="utf-8") as fh:
writer = csv.DictWriter(fh, fieldnames=["id", "title", "price"])
writer.writeheader()
while url and seen < max_pages:
if not robots.can_fetch(sess.headers["User-Agent"], url):
print("robots.txt disallows", url)
break
resp = sess.get(url, timeout=(5, 25))
resp.raise_for_status()
rows, url = parse_listing(resp.text, resp.url)
writer.writerows(rows)
seen += 1
time.sleep(random.uniform(1.0, 2.5))
Writing rows as you go means a crash at page 150 still leaves 149 pages of data on disk. For long jobs, also record the last URL processed so a restart can resume instead of starting over. The tuple timeout (5, 25) sets separate connect and read limits.
When responses go wrong
Most failures fall into a few groups, and each needs a different reaction:
| What you get | What it usually means | Reasonable reaction |
|---|---|---|
| 429 Too Many Requests | You are too fast | Honor Retry-After, slow the whole crawl |
| 500, 502, 503, 504 | Server or gateway trouble | Retry with backoff, then skip and log |
| 403 with normal HTML | Blocked by a rule or header check | Check headers, pacing, IP reputation |
| 200 with a challenge page | A CAPTCHA or bot check | Detect it, solve it, retry once |
| 200 with missing fields | Layout changed or content is JS rendered | Alert, inspect, update selectors |
The last two rows are the sneaky ones because the status code looks fine. Validate what you parse: if a listing page suddenly yields zero rows, stop and alert rather than writing an empty file. The 429 note covers rate limit handling in more depth.
Where CAPTCHAs fit
A well paced scraper on ordinary public pages may never see a CAPTCHA. They tend to appear on search forms, login pages, and sites behind bot management products when traffic looks automated. When one shows up, treat it as one more response type:
- Detect it. Look for markers in the response: a
data-sitekeyattribute for reCAPTCHA or Turnstile, a 405 page withgokuPropsfor AWS WAF, a 403 fromgeo.captcha-delivery.comfor DataDome. - Solve it. Send the page URL and key to a solving API and poll for the answer. Token types return a string for the form; firewall types such as AWS WAF return a cookie for the session.
- Use the answer once and retry the original request. Keep the session so cookies earned along the way persist.
The code is short. Here is the shape of a cookie based solve inside the crawler above, using the AWS WAF task as the example:
def clear_waf(sess: requests.Session, url: str, api_key: str) -> None:
job = sess.post("https://gatesolver.com/createTask", timeout=30, json={
"clientKey": api_key,
"task": {"type": "AntiAwsWafTaskProxyLess", "websiteURL": url}}).json()
for _ in range(40):
time.sleep(3)
st = sess.post("https://gatesolver.com/getTaskResult", timeout=30, json={
"clientKey": api_key, "taskId": job["taskId"]}).json()
if st.get("status") == "ready":
site_host = urlparse(url).hostname
sess.cookies.set("aws-waf-token", st["solution"]["cookie"], domain=site_host)
return
if st.get("errorId") or st.get("status") == "failed":
break
raise RuntimeError("could not clear the AWS WAF check")
A solve costs a fraction of a cent (AWS WAF is $1.40 per 1,000 at the time of writing, and failed tasks are free), but the bigger win is usually upstream: slower pacing, consistent headers and a good IP reduce how often the check appears at all. The article on CAPTCHA solving in web scraping goes deeper into both sides.
Keep it legal and considerate
Collect public data, respect robots.txt and terms that apply to you, avoid personal data unless you have a lawful basis, and never put a site under load it was not built for. A crawler that identifies itself, sleeps between requests and runs at quiet hours rarely causes trouble for anyone. Our article on whether web scraping is legal covers the main questions.
Growing beyond one script
When the job outgrows a single loop, you will want concurrency, a queue of URLs, deduplication and structured output. At that point a framework pays for itself: Scrapy gives you all of these out of the box, and Scrapy vs Beautiful Soup explains when to switch. If the site needs JavaScript, add a browser only for the pages that need it; the Scrapy vs Selenium comparison helps you plan that hybrid. For async HTTP in plain Python, HTTPX and aiohttp are the usual next steps.
Common questions
Do I need lxml for Beautiful Soup?
No, Python's built in html.parser works. lxml is faster and more forgiving with broken markup, so it is worth installing when you can.
How fast should a Python scraper send requests?
There is no single number. Start with a pause of one to a few seconds per request to the same site, watch for 429 responses, and slow down if they appear.
Should I always set a timeout in requests?
Yes. requests has no default timeout, so a stalled connection can hang your scraper indefinitely without one.
When should I switch from requests to a browser?
When the data is rendered by JavaScript and no JSON endpoint supplies it. Check the Network panel first; a JSON endpoint is usually easier.
How often will my scraper meet CAPTCHAs?
It depends on the site and your traffic pattern. Polite pacing and consistent headers keep them rare, and a solving API covers the cases that remain.
Keep reading
- Web scrapingWeb scraping means fetching pages and pulling structured data out of them, within the legal and ethical limits of the sites involved.
- Python RequestsThe popular Python HTTP library with sessions and a simple API, and the reasons protected sites spot it so quickly.
- Solving CAPTCHAs in web scraping pipelinesAn architecture for scrapers that meet CAPTCHAs: detect challenges as their own outcome, solve in a separate stage, retry with clear limits.
- Scrapy vs Beautiful SoupA crawling framework and an HTML parser are different tools: what each handles, when to pick which, and how to combine them.