Python web scraping tutorial: from first request to a polite crawler
By the ProxyOnly team · 25 Nov 2026 · 5 min read
A working Python scraper built in stages: one request, parsing, following pagination, error handling, and the manners that keep a crawler running.
This builds a working scraper in Python, one stage at a time. Every snippet here was run before it was published, and the output quoted is what it printed.
We scrape quotes.toscrape.com, a site made for practising on. Do not point tutorial code at a live commercial site while you are learning; you will make every beginner mistake at somebody else's expense. Is web scraping legal covers the rules that apply once you move to a real target.
What you need
pip install requests beautifulsoup4Two libraries. requests fetches pages, beautifulsoup4 parses the HTML. You will see Scrapy and Playwright recommended too, and both are excellent for what they do, but neither is where to start.
Stage 1: one request
import requests
r = requests.get("https://quotes.toscrape.com/page/1/", timeout=10)
print(r.status_code, len(r.text), "bytes")Three things in three lines are worth noticing. The timeout is not optional: requests has no default, so without it a hung server hangs your script forever. The status code is the first thing to check, not the body. And r.text is the HTML as a string, which is all a scraper ever receives. There is no page, no JavaScript, no rendering, just bytes.
Check the status before you parse:
r.raise_for_status()That raises on 4xx and 5xx instead of letting you parse an error page as though it were data, which is the single most common way a scraper produces confident nonsense.
Stage 2: pull data out
Open the page in a browser, right-click a quote and choose Inspect. You will find each quote wrapped in div.quote, with the text in span.text, the author in small.author and the tags in a.tag. Those selectors are the scraper.
from bs4 import BeautifulSoup
soup = BeautifulSoup(r.text, "html.parser")
for q in soup.select("div.quote"):
text = q.select_one("span.text").get_text(strip=True)
author = q.select_one("small.author").get_text(strip=True)
tags = [t.get_text(strip=True) for t in q.select("a.tag")]
print(author, "|", text[:50], "|", tags)select takes CSS selectors and returns every match. select_one returns the first or None. Use get_text(strip=True) rather than .string, which returns None when an element has mixed content and is a common source of silent empty fields.
Our XPath and CSS selector cheat sheet covers choosing selectors that survive a redesign, and the BeautifulSoup tutorial goes deeper on the parsing API.
Stage 3: follow the pagination
A single page is a demo. The useful version follows the next link until there is not one.
import time
import requests
from bs4 import BeautifulSoup
BASE = "https://quotes.toscrape.com"
s = requests.Session()
s.headers.update({"User-Agent": "ProxyOnly-example/1.0 (+https://proxyonly.com/blog)"})
rows, url, pages = [], "/page/1/", 0
while url and pages < 3:
r = s.get(BASE + url, timeout=10)
r.raise_for_status()
soup = BeautifulSoup(r.text, "html.parser")
for q in soup.select("div.quote"):
rows.append({
"text": q.select_one("span.text").get_text(strip=True),
"author": q.select_one("small.author").get_text(strip=True),
"tags": [t.get_text(strip=True) for t in q.select("a.tag")],
})
nxt = soup.select_one("li.next a")
url = nxt["href"] if nxt else None
pages += 1
time.sleep(1)
print(f"{pages} pages, {len(rows)} quotes")We ran this and it printed 3 pages, 30 quotes, with the first row being Albert Einstein and the tags ['change', 'deep-thoughts', 'thinking', 'world'].
Four things changed from stage 2, and each is the difference between a script and a crawler.
A Session reuses the TCP connection and TLS handshake across requests instead of starting fresh each time. On a crawl of any size this is the largest easy speedup available.
The User-Agent says who is calling and gives a URL to complain to. A default python-requests/2.x is an invitation to be blocked, and a fake Chrome string is a lie that stops working the moment anything checks. Honest and contactable survives longest.
The page limit is a stop condition. Write it before you write the loop. Every scraper author has at some point run an unbounded while against a site with circular pagination.
The time.sleep(1) is the manners. One request per second is slow on purpose.
Stage 4: survive the real web
The loop above assumes everything works. On a real site it will not. Three failures matter most.
Transient server errors deserve a retry with increasing waits. Permanent ones do not. urllib3 handles this for you:
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(total=4, status_forcelist=[429, 502, 503, 504],
respect_retry_after_header=True, backoff_factor=0.5)
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))Note which codes are in that list. A 429 or a 503 means try again later. A 400 or a 405 means your request is wrong, and retrying it is pure waste.
Missing elements should not crash the run. A page with a changed layout returns None from select_one, and .get_text() on None ends the job at row 4,000 of 5,000:
def text_of(node, selector):
found = node.select_one(selector)
return found.get_text(strip=True) if found else NoneSave as you go. Append each page's rows to a file rather than holding everything in memory until the end. A crawl that dies at 95 percent and has written nothing has produced nothing.
Stage 5: when one address is not enough
Everything above is a well-behaved crawler reading a public site slowly, and for most jobs that is the whole story. Three situations change it.
The site is rate limited per address and you need more throughput than one address allows. The site serves different content by country and you need to see a specific one. Or your own address has been blocked by a filter that cannot tell you apart from an abusive crawler.
A proxy routes the request through another machine, so the site sees that address instead of yours:
proxies = {"http": "http://user:pass@203.0.113.10:8080",
"https": "http://user:pass@203.0.113.10:8080"}
r = session.get(url, proxies=proxies, timeout=10)Be honest with yourself about which of the three you have. If a site is blocking you because you sent 50 requests a second, more addresses is not the fix, it is the same mistake distributed. Slow down first and see whether the problem goes away, because that is both cheaper and the thing that makes your crawler sustainable. Why websites block IPs and proxies covers what blocking actually keys on, and proxies for web scraping covers choosing a type when you do need one.
Where to go next
Scale up to Scrapy when you outgrow a loop. It gives you concurrency, retries, pipelines and throttling as configuration rather than code. The Scrapy tutorial builds the first spider.
Reach for a browser only when the data genuinely is not in the HTML. Check first: open the network tab, reload, and look for a JSON request that already contains what you want. Calling that endpoint directly is faster and more stable than driving a browser. When you do need one, browser automation behind a proxy and Playwright vs Selenium vs Puppeteer cover the options.
Go faster with concurrency rather than a different library. requests vs httpx vs aiohttp has the benchmark: sequential code runs at about 17 requests per second whichever client you pick, and concurrency is worth an order of magnitude more than the choice between them.
Try it yourself
Create an account, add funds from US$1 and order a proxy in the country you need.
Keep reading
25 Nov 2026 · Web scraping
Web scraping API vs proxies vs building it yourself
Scraping API, raw proxies, or your own stack. What each actually costs, what you give up, and the cases where we would tell you to buy the API instead.
25 Nov 2026 · Web scraping
Headless browsers explained: what they are and when to use one
A headless browser is a real browser without a window. What it does for scraping and testing, what it costs in speed, and when plain HTTP is better.