Guides

Python web scraping: Requests + BeautifulSoup, with real headers

By · Published

TL;DR

  • Python web scraping needs two free libraries: Requests fetches the page, BeautifulSoup finds the data in it.
  • A bare script has no timeout, no retries, breaks £ signs and announces itself as python-requests.
  • Copy the script below. It fixes all four, scrapes 1,000 practice books to CSV, and shows you when Requests stops being enough.

Install two libraries and fetch one page

Open a terminal and install Requests, BeautifulSoup and lxml (a fast HTML parser):

pip install requests beautifulsoup4 lxml

The package is called beautifulsoup4. Plain BeautifulSoup on pip is the old version 3, not what you want.

Now fetch a page from Books to Scrape, a fake bookstore made for practice. It has 1,000 books, 20 per page, over 50 pages.

import requests
from bs4 import BeautifulSoup

r = requests.get("https://books.toscrape.com/catalogue/page-1.html", timeout=20)
r.raise_for_status()                      # stop on 403, 404, 500 ...
soup = BeautifulSoup(r.content, "lxml")   # r.content, not r.text (see the £ section)

for book in soup.select("article.product_pod"):
    print(book.select_one("h3 a")["title"], book.select_one("p.price_color").get_text(strip=True))

The first book on the page: A Light in the Attic, £51.77.

New to all this and want your AI to write the code? Start with How to scrape a website. This page is the code itself, explained.

What each piece does:

  • requests sends the request and hands you a Response. r.status_code is the 3-digit answer, r.content the raw bytes, r.text those bytes turned into text.
  • beautifulsoup4 is the name you install. In code you import bs4. It turns HTML into a tree you can search.
  • lxml is the parser underneath. You name it in the BeautifulSoup() call.

raise_for_status() raises an error on any 4xx or 5xx answer and does nothing on a 200. Without it, a 404 page parses without complaint and you get zero books.

Requests also follows redirects by itself, for every method except HEAD. r.history lists the hops. So r.url can differ from the URL you asked for.

Find the data with CSS selectors

select() returns every match, select_one() only the first. Both take CSS selectors: short addresses for parts of a page, the same ones your browser’s dev tools show.

This is what each book on the list page looks like, and the selector that grabs each part:

you want selector how you read it
one book article.product_pod loop over these
full title h3 a ["title"] (the link text is cut: “A Light in the …”)
price p.price_color .get_text(strip=True) → £51.77
stock p.availability .get_text(strip=True) → In stock
stars p.star-rating ["class"][1] → Three
book page h3 a ["href"], made absolute with urljoin
next page li.next a ["href"] → page-2.html

Pass the parser name every time ("lxml"). Without it, BeautifulSoup picks whatever parser is installed, so the same script can behave differently on another computer.

  • ["class"] gives a list, not a string, because class can hold several values. The star tag is <p class="star-rating Three">, so item [1] is the rating word.
  • get_text(strip=True) trims the spaces and line breaks around the text. The stock line has plenty.
  • Links on the page are relative (a-light-in-the-attic_1000/index.html). urljoin(page_url, href) turns them into full URLs.
  • Speed: the Beautiful Soup docs say it parses significantly faster with lxml than with html.parser. If parsing is your bottleneck, the same docs suggest working with lxml directly.
  • The book page itself keeps its details in a table: <th>UPC</th><td>a897fe39b1053632</td>. Read it with select("table tr"), then each row’s th and td.

Your £ turns into £: read bytes, not text

Use r.text on Books to Scrape and every price prints as £51.77. Here’s why.

  • The site’s Content-Type header says text/html, with no character set.
  • In that case Requests follows an old rule (RFC 2616) and decodes the page as ISO-8859-1.
  • The page is really UTF-8. It says so in a <meta> tag inside the HTML, but Requests only looks at the header here.

The fix is one word. Give BeautifulSoup the raw bytes, r.content, and it works out the encoding itself. Or set r.encoding = "utf-8" before you touch r.text.

Computers store text as bytes. An encoding is the rule that turns bytes into letters.

  • In UTF-8, £ takes two bytes: 0xC2 0xA3.
  • ISO-8859-1 (also called latin-1) maps each byte to one character. So it reads those two bytes as two characters: Â and £.

That’s the stray Â. Nothing is lost: the bytes are fine, only the reading was wrong.

The other practice site behaves differently. Quotes to Scrape sends content-type: text/html; charset=utf-8, so r.text works there. That’s how one script can be fine on one site and garble the next.

Advice: always hand r.content to BeautifulSoup. It detects the encoding with a helper called Unicode, Dammit, and soup.original_encoding shows what it picked.

Use a Session, a timeout and retries

A plain requests.get() has three weak spots. Out of the box, Requests:

  1. never times out. A silent server can hang your script for minutes or more.
  2. never retries a failed connection.
  3. opens a new connection and forgets cookies on every call.

A Session fixes the third. It keeps cookies between requests and reuses the connection to the same site, which is faster. Retries plug into it:

import requests
from requests.adapters import HTTPAdapter
from urllib3.util import Retry

def make_session(headers):
    retry = Retry(
        total=3,
        backoff_factor=1,                          # waits 0 s, 2 s, 4 s between tries
        status_forcelist=[429, 500, 502, 503, 504],
        raise_on_status=False,                     # out of tries: give back the last response
    )
    s = requests.Session()
    s.mount("https://", HTTPAdapter(max_retries=retry))
    s.mount("http://", HTTPAdapter(max_retries=retry))
    s.headers.update(headers)
    return s

Then pass a timeout on every call: s.get(url, timeout=(3.05, 27)). That’s 3.05 seconds to connect and 27 to wait for data, the docs’ own example.

What the Retry settings do, from the urllib3 docs:

  • status_forcelist: retry on these codes. 429 (too many requests) and 5xx (server trouble) often pass if you wait. A 403 won’t, so it’s not in the list.
  • backoff_factor: the wait is factor × 2^(retries so far), capped at 120 seconds by backoff_max. The first retry comes right away.
  • Retry-After: on 413, 429 and 503, urllib3 obeys the site’s Retry-After header by default and sleeps that long instead. It accepts up to 21,600 seconds (6 hours) unless you lower retry_after_max.
  • Methods: only “safe to repeat” methods retry by default (GET, HEAD, PUT, DELETE, OPTIONS, TRACE). POST does not.
  • Timeouts aren’t a stopwatch: the read timeout counts the gap between bytes from the server, not the whole download.

Headers: what Requests sends vs what Chrome sends

Headers are the short notes every request carries. The User-Agent one says which program is asking.

Requests sends four headers by default. Chrome 152 on a Mac sends 14, in this order:

header Requests default Chrome 152 (macOS)
sec-ch-ua not sent "Chromium";v="152", "Not?A_Brand";v="24", "Google Chrome";v="152"
sec-ch-ua-mobile not sent ?0
sec-ch-ua-platform not sent "macOS"
upgrade-insecure-requests not sent 1
user-agent python-requests/<version> Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36
accept */* text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7
sec-fetch-site · -mode · -user · -dest not sent none · navigate · ?1 · document
accept-encoding gzip, deflate (+ br, zstd if installed) gzip, deflate, br, zstd
accept-language not sent en-US,en;q=0.9
priority not sent u=0, i
cache-control not sent max-age=0
connection keep-alive not sent

A site that sees python-requests/2.34.2 knows it’s a script before it reads anything else. So send the browser set:

CHROME = {
    "sec-ch-ua": '"Chromium";v="152", "Not?A_Brand";v="24", "Google Chrome";v="152"',
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": '"macOS"',
    "upgrade-insecure-requests": "1",
    "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
                  "(KHTML, like Gecko) Chrome/152.0.0.0 Safari/537.36",
    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,"
              "image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "sec-fetch-site": "none",
    "sec-fetch-mode": "navigate",
    "sec-fetch-user": "?1",
    "sec-fetch-dest": "document",
    "accept-language": "en-US,en;q=0.9",
    "priority": "u=0, i",
}

Three rules for a user agent that doesn’t give you away:

  1. Keep the set consistent. Chrome 152 in user-agent means 152 in sec-ch-ua too, and "macOS" means a Mac user agent.
  2. Leave accept-encoding out. Requests can only unpack br and zstd if the extra packages are installed. Let it fill in what it can actually read.
  3. Don’t rotate random user agents. Your headers change, but your connection still looks like Python. That mismatch is a signal on its own (why).
  • Chrome’s user agent ends in 152.0.0.0: the minor version numbers are all zeros. Copy it as is.
  • The whole set comes from curl-impersonate’s recorded Chrome 152 signature. The Windows recording differs in two lines: sec-ch-ua-platform: "Windows" and a user agent with Windows NT 10.0; Win64; x64.
  • Chrome sends these over HTTP/2. Requests can’t: the curl_cffi feature matrix marks it with no HTTP/2 and no fingerprint control. That’s the limit of fixing headers alone.

The whole scraper: 50 pages to a CSV

Put CHROME and make_session from above at the top of the file, then:

import csv, random, time
from urllib.parse import urljoin
from bs4 import BeautifulSoup

START = "https://books.toscrape.com/catalogue/page-1.html"
MAX_PAGES = 100          # safety cap, so a loop can never run forever
rows, url = [], START

with make_session(CHROME) as s:
    for page in range(1, MAX_PAGES + 1):
        r = s.get(url, timeout=(3.05, 27))
        if r.status_code != 200:
            print(f"Stopped: status {r.status_code} on {url}")
            break
        soup = BeautifulSoup(r.content, "lxml")
        books = soup.select("article.product_pod")
        if not books:
            print(f"0 books on {url}: layout changed, JavaScript page or a block page")
            break
        for b in books:
            link = b.select_one("h3 a")
            rows.append({
                "title": link["title"],
                "price": b.select_one("p.price_color").get_text(strip=True),
                "stock": b.select_one("p.availability").get_text(strip=True),
                "stars": b.select_one("p.star-rating")["class"][1],
                "url": urljoin(url, link["href"]),
            })
        print(f"Page {page}: {len(books)} books")
        nxt = soup.select_one("li.next a")
        if not nxt:
            break                                  # page 50 has no "next"
        url = urljoin(url, nxt["href"])
        time.sleep(random.uniform(1, 2))           # be polite: 1-2 s between pages

with open("books.csv", "w", newline="", encoding="utf-8-sig") as f:
    w = csv.DictWriter(f, fieldnames=["title", "price", "stock", "stars", "url"])
    w.writeheader()
    w.writerows(rows)
print(f"Saved {len(rows)} rows")

It should end with Saved 1000 rows. Each check prints why it stopped, so you know what to fix.

Each line has a job:

  • MAX_PAGES = 100: the site has 50 pages, so the cap never bites here. It stops a “next” link that loops back to itself.
  • status_code != 200: the Session already retried 429 and 5xx three times. What’s left won’t fix itself.
  • The 0-books check catches a block page or a JavaScript page that came back with a 200.
  • random.uniform(1, 2): 49 pauses for 50 pages, so 49 to 98 seconds of waiting. Slow on purpose.
  • newline="" is what the csv docs ask for when you open the file.
  • utf-8-sig writes 3 bytes (0xEF 0xBB 0xBF) at the start. The codecs docs call it a signature that helps programs guess the file is UTF-8.

Advice: rows wait in memory until the end. On a long crawl, write each page’s rows as you go, so a crash keeps them.

Log in once, stay logged in

The Session also carries a login. Quotes to Scrape has a practice login form with a hidden CSRF token (a one-time code the form must send back). Any username and password work.

with make_session(CHROME) as s:
    form = BeautifulSoup(s.get("https://quotes.toscrape.com/login", timeout=20).content, "lxml")
    token = form.select_one("input[name=csrf_token]")["value"]
    s.post("https://quotes.toscrape.com/login", timeout=20,
           data={"csrf_token": token, "username": "demo", "password": "demo"})
    home = s.get("https://quotes.toscrape.com/", timeout=20)
    print("Logout" in home.text)   # True: the cookie stayed in the session

The token is also stored in the session cookie the login page sets. That’s why the form and the login must go through the same Session.

CSRF stands for cross-site request forgery: an attack where another site tricks a logged-in user into sending a request they didn’t mean to send. The hidden token blocks it, because only someone who loaded the real form has it.

What happens, step by step:

  1. The GET to /login sets a session cookie and puts a fresh csrf_token in the form.
  2. The POST sends the token back with the username and password.
  3. The site answers 302 (go elsewhere) and points to the home page. Requests follows it by itself.
  4. Logged in, the home page shows a “Logout” link and a Goodreads link under every quote.

If a login form only appears after JavaScript runs, Requests never sees it. That’s a job for a browser: Scrape JavaScript sites.

Real headers still blocked? Switch to curl_cffi

Headers travel on top of the connection. Before any header arrives, the site already sees how your client opened the secure connection: the TLS handshake. Requests can’t change its handshake, so it still looks like Python.

curl_cffi copies a real browser’s handshake and HTTP/2 settings, and it mimics the Requests API. The change is small:

pip install curl_cffi --upgrade
from curl_cffi import Session

with Session(impersonate="chrome") as s:      # newest Chrome profile it ships
    r = s.get("https://books.toscrape.com/catalogue/page-1.html", timeout=20)
  • Drop your CHROME dict here. With impersonate, curl_cffi adds the matching browser headers itself. Anything you pass in headers= overrides them.
  • impersonate="chrome" always picks the newest profile. Pin one, like "chrome152", if you need the same fingerprint every run. The docs list every target.
  • It needs Python 3.10 or newer.

What the handshake is and how sites read it: How to avoid getting blocked.

TLS is the encryption behind https. Before any data moves, your client says hello and lists what it supports. Chrome’s hello has its own list and order of ciphers and extensions. Python’s is different, and sites can turn that hello into a fingerprint (JA3 or JA4).

Test it yourself. The curl_cffi docs use https://tls.browserleaks.com/json, which sends back your fingerprint. Compare the ja3n_hash from Requests with the one from curl_cffi.

Two differences to know before you switch:

  • No mount(). curl_cffi can’t take adapters, so the urllib3 Retry from make_session doesn’t carry over. Its feature matrix lists native retry instead. Or run curl_cffi inside Requests with the curl-adapter project.
  • Proxies: the Requests-style proxies= dict works, but the docs prefer proxy=....

When it breaks, read what it printed

it printed what it usually means read
status 403 the site refused you 403 Forbidden
status 403, page mentions 1020 a Cloudflare rule the owner set blocked you Cloudflare 1020
a “Just a moment…” page Cloudflare wants to test your browser Just a moment
status 429 too many requests, too fast 429 Too Many Requests
0 books, but you see them in your browser the page is built by JavaScript Scrape JavaScript sites
any other code look up the number Errors and status codes

The status code isn’t always the whole story. Two checks help:

  • Cloudflare’s 1020 page comes with a 403. Same code as a plain refusal, different cause: a rule the site owner wrote. Look for 1020 in r.text.
  • Every Cloudflare challenge page carries the header cf-mitigated: challenge, whatever its status code. Test r.headers.get("cf-mitigated") == "challenge".

Unsure? Save what came back and open it in your browser:

open("debug.html", "wb").write(r.content)

A login page, a CAPTCHA or a near-empty page full of <script> tags tells you more than the number does.

Paste into your AI

I have a Python scraper built on requests + BeautifulSoup (lxml parser), with a Session,
urllib3 Retry on 429/5xx, timeout=(3.05, 27) and a full Chrome 152 header set.
Adapt it to this site: <URL of the list page>
Fields I want, one row per item: <field 1>, <field 2>, <field 3>

1. Look at the HTML of that page and give me the CSS selector for one item and for each field.
   Read full values from attributes (title="", href="") when the visible text is cut short.
2. Find the "next page" link and keep the MAX_PAGES cap.
3. Keep BeautifulSoup(r.content, "lxml"), the 1-2 second pause and the stop-on-error checks.
4. If the page needs JavaScript, say so instead of guessing selectors.
5. If I paste you a status code or a block page, tell me which fix to try first:
   slower pace, headers, curl_cffi impersonate, or a browser.

Each line guards a part of the script that’s easy to lose when code gets rewritten:

  • Attributes first: list pages often cut long text short, like the book titles here.
  • MAX_PAGES and the pause keep one mistake from turning into a flood of requests.
  • r.content keeps the £ fix.
  • The JavaScript line stops it from inventing selectors for HTML that was never sent.

Give it evidence, not a summary: the status code, the URL, the first 30 lines of the body and the response headers. Remove cookies, passwords and API keys before you paste.

Advice: when it hands back code, ask it to point to the timeout, the retries and the stop checks. If one is gone, ask for it back.

Tools for this

ToolPrice
Beautiful Soup: Python library for pulling data out of HTML and XML pages. Parses messy markup and lets you search the tree.Free
curl_cffi: Python HTTP client on curl-impersonate that can copy a browser's TLS, JA3 and HTTP/2 fingerprints.Free
HTTPX: Python HTTP client with sync and async APIs and HTTP/2 support.Free
lxml: Python XML and HTML toolkit with XPath and CSS selector support, built on libxml2.Free
Scrapy: Parsel: Library from the Scrapy team to extract data from HTML or XML with XPath or CSS selectors. Scrapy: Python framework for crawling sites and extracting data: request queue, retries, pipelines, exports. Large plugin ecosystem.Parsel Free Scrapy Free Free
Requests: The classic simple HTTP library for Python.Free
selectolax: Fast HTML5 parser for Python with CSS selectors, using the Modest and Lexbor engines.Free

Sources

  1. Requests docs: Advanced Usage (Sessions, Encodings, Retries, Timeouts) requests.readthedocs.io
  2. Requests source: default_headers and default_user_agent requests.readthedocs.io
  3. urllib3 docs: Retry (backoff, status_forcelist, Retry-After) and make_headers urllib3.readthedocs.io
  4. Beautiful Soup docs: CSS selectors, parsers, encodings, multi-valued attributes crummy.com
  5. Books to Scrape: practice bookstore (1,000 books, 50 pages) books.toscrape.com
  6. Quotes to Scrape: practice login form with a CSRF token quotes.toscrape.com
  7. curl-impersonate: recorded Chrome 152 (macOS) request signature github.com
  8. curl-impersonate: recorded Chrome 152 (Windows) request signature github.com
  9. curl_cffi docs: Features and feature matrix vs requests, httpx curl-cffi.readthedocs.io
  10. curl_cffi docs: Quick Start (impersonate, default headers, Python 3.10+) curl-cffi.readthedocs.io
  11. curl_cffi docs: Supported impersonate targets curl-cffi.readthedocs.io
  12. curl_cffi docs: API reference (Session impersonate) curl-cffi.readthedocs.io
  13. curl_cffi docs: Compatibility with requests (no adapters, proxy=) curl-cffi.readthedocs.io
  14. Requests docs: Quickstart (raise_for_status, redirects and history) requests.readthedocs.io
  15. Python docs: csv (open files with newline='') docs.python.org
  16. Python docs: codecs (latin-1, utf-8-sig signature) docs.python.org
  17. FileFormat.info: U+00A3 POUND SIGN (UTF-8 bytes 0xC2 0xA3) fileformat.info
  18. OWASP: Cross Site Request Forgery (CSRF) community.owasp.org
  19. Cloudflare docs: Error 1020 (returned with HTTP 403) developers.cloudflare.com
  20. Cloudflare docs: Detect a Challenge Page response (cf-mitigated) developers.cloudflare.com