Skip to content

Python Requests for scraping: sessions, headers, retries and proxies

By the ProxyOnly team · 16 Nov 2026 · 5 min read

How to use Python Requests for scraping: sessions and headers, timeouts, retries that honour Retry-After, proxies, rotating across several proxies, and one setting that silently overrides them.

Requests is the library most Python scrapers start with, and it does most jobs well once a few settings are right. This guide covers the parts that matter for scraping: sessions, headers, timeouts, retries, proxies and rotation. Every example was run on 16 November 2026 with Requests 2.34.2 and urllib3 2.8.0 on Python 3.10, against httpbin.org and test servers on our own machine, and the output shown is what it printed.

If you are new to scraping, what is web scraping explains the idea, and how to scrape a website explains when a library like Requests is enough.

Use a session

A Session keeps connections open between requests, which is faster, and keeps cookies and default headers. Set the headers once and every request carries them.

import requests
session = requests.Session()
session.headers.update({
    "User-Agent": "price-checker/1.0 (+https://example.org/bot)",
    "Accept-Language": "en-US,en;q=0.9",
})
r = session.get("https://httpbin.org/headers", timeout=(5, 20))
print(r.status_code, r.json()["headers"]["User-Agent"], "|", r.json()["headers"]["Accept-Language"])
session.get("https://httpbin.org/cookies/set?visited=yes", timeout=(5, 20))
print(session.get("https://httpbin.org/cookies", timeout=(5, 20)).json())
200 price-checker/1.0 (+https://example.org/bot) | en-US,en;q=0.9
{'cookies': {'visited': 'yes'}}

The cookie set by the first request came back on the second without any code. The user agent names the bot and gives a URL where a site owner can read about it, which is the honest choice for a scraper. User agents explained covers what Requests sends when you set nothing.

Always set a timeout

Requests waits indefinitely by default. A stuck server or proxy then stops your whole job without an error. Pass timeout on every call. A tuple sets the connect and read limits separately, so (5, 20) allows 5 seconds to connect and 20 seconds between bytes of the response.

Retry the failures worth retrying

Some failures are temporary: a 503 during maintenance, a 429 asking you to slow down, a 502 from an overloaded gateway. urllib3, which Requests uses underneath, can retry them for you and wait as long as the server asks in its Retry-After header.

import time
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(
    total=4,
    backoff_factor=0.5,
    status_forcelist=[429, 500, 502, 503, 504],
    allowed_methods=["GET", "HEAD"],
    respect_retry_after_header=True,
)
session = requests.Session()
session.mount("http://", HTTPAdapter(max_retries=retry))
session.mount("https://", HTTPAdapter(max_retries=retry))
start = time.time()
r = session.get("http://127.0.0.1:9001/flaky", timeout=10)
print(r.status_code, r.text, f"after {time.time() - start:.1f}s")

Our test server answers /flaky with 503 and Retry-After: 1 twice, then succeeds.

200 hello from upstream after 2.0s

The two retries waited the second each that the server asked for, and the code saw only the final success. Keep allowed_methods to safe methods so a retry never repeats a form submission. Retries are no substitute for going slowly in the first place, as rate limiting explained describes.

Send requests through a proxy

Requests takes a dictionary that maps the scheme of the URL you request to a proxy URL. Use the same proxy for both, and keep the proxy URL itself http://, because the connection to the proxy is plain HTTP even when the site is HTTPS.

import requests
proxy = "http://USERNAME:PASSWORD@HOST:PORT"
proxies = {"http": proxy, "https": proxy}
r = requests.get("https://httpbin.org/ip", proxies=proxies, timeout=20)
print(r.status_code, r.json())

Replace the four values with the ones on your order page. We ran it with a test proxy that requires a login, and the proxy logged the tunnel to httpbin.org. If your password contains characters such as @, : or /, percent-encode it with urllib.parse.quote(password, safe="") before putting it in the URL. What to look for when you buy a proxy server includes a checker script that does this for a whole list.

The setting that overrides your proxies

This one costs people hours. If an HTTPS_PROXY or HTTP_PROXY environment variable is set, it overrides the proxies you put on a session with session.proxies. The Requests documentation warns about it, and our test shows it. We set the environment variable to one test proxy and session.proxies to another, and counted the requests each one logged.

session.proxies only:      8104 saw 1 | 8107 saw 0
with trust_env = False:    8104 saw 0 | 8107 saw 1
proxies= on the request:   8104 saw 0 | 8107 saw 1

The environment's proxy on port 8104 won, and the session's proxy on 8107 was ignored. Two fixes worked: setting session.trust_env = False, which makes the session ignore the environment, or passing proxies= on each request, as in the example above. The second is what the documentation recommends.

Spread requests across several proxies

A static proxy keeps one address for the whole rental period. To spread a job across several addresses, buy several and choose one per request in your own code.

from itertools import cycle
import requests
PROXIES = cycle(["http://127.0.0.1:8104", "http://127.0.0.1:8107"])
session = requests.Session()
for page in range(1, 5):
    proxy = next(PROXIES)
    r = session.get(f"http://127.0.0.1:9201/?page={page}", proxies={"http": proxy, "https": proxy}, timeout=20)
    print(page, proxy, r.status_code)
1 http://127.0.0.1:8104 200
2 http://127.0.0.1:8107 200
3 http://127.0.0.1:8104 200
4 http://127.0.0.1:8107 200

The two test proxies logged pages 1 and 3, and 2 and 4. With real proxies, put your own proxy URLs in the list. Keep cookies apart if the sites should not link the requests: a session's cookies travel with every request whichever proxy it uses, so use one session per proxy when that matters. Rotating proxies covers when rotation helps and when it does not.

Handle errors by type

Requests raises different exceptions for different failures, and each one points at a different fix.

  • requests.exceptions.ProxyError: the proxy refused you or could not be reached. A 407 in the message means the login is wrong.
  • requests.exceptions.ConnectTimeout and ReadTimeout: nothing answered in time.
  • requests.exceptions.SSLError: the secure handshake failed.
  • requests.exceptions.HTTPError: raised by response.raise_for_status() when the site returned an error status.

Every common proxy error lists the exact messages and their causes.

When to use something else

Requests sends one request at a time and speaks HTTP/1.1. For thousands of pages in parallel, an async client such as httpx or aiohttp is a better fit, and a crawling framework such as Scrapy handles scheduling, retries and politeness for you. For pages that build their content with JavaScript, you need a browser, as Playwright vs Selenium vs Puppeteer compares. The Python Requests setup guide shows the proxy settings again in short form.

Try it yourself

Create an account, add funds from US$1 and order a proxy in the country you need.

Keep reading