Requests: Fetching Pages the Right Way

Requests: Fetching Pages the Right Way in Python: Before you can parse a web page you have to get it.

Concept Explanation

Before you can parse a web page you have to get it. Every scraper, every API client, every "check if the site is up" script starts with one HTTP request.

Python ships with urllib.request in the standard library, and almost nobody uses it directly — the API is clumsy. The community standard is requests, a library whose stated goal is "HTTP for humans." Compare:

# urllib -- the standard library
from urllib.request import urlopen
html = urlopen("https://example.com").read().decode("utf-8")

# requests -- what people actually write
import requests
html = requests.get("https://example.com").text

Installing It

pip install requests

The Response Object

requests.get() does not return the page. It returns a Response, and the useful parts are:

AttributeGives you
.status_code200 = OK, 404 = missing, 403 = blocked, 500 = their bug
.textThe body decoded to a str
.contentThe body as raw bytes — use this for images and PDFs
.json()The body parsed from JSON into a dict
.headersA case-insensitive dict of response headers
.okTrue for any status below 400

The Four Verbs You Will Actually Use

MethodPurpose
requests.get(url)Read something
requests.post(url, json=...)Create something
requests.put(url, json=...)Replace something
requests.delete(url)Remove something

Query Strings: Let the Library Build Them

Never glue query parameters onto a URL by hand — spaces and & characters will break it. Pass a dict:

requests.get("https://api.example.com/search", params={"q": "python books", "page": 2})
# -> https://api.example.com/search?q=python+books&page=2

Code Example #1 (Basic)

A request that checks its own result instead of assuming success.

import requests

url = "https://httpbin.org/get"

try:
    response = requests.get(url, timeout=10)
    response.raise_for_status()      # turns 4xx/5xx into an exception
except requests.exceptions.Timeout:
    print("The server took too long to answer.")
except requests.exceptions.HTTPError as err:
    print(f"Server returned an error: {err}")
except requests.exceptions.RequestException as err:
    print(f"Network problem: {err}")
else:
    print("Status:", response.status_code)
    print("Content type:", response.headers["Content-Type"])
    print("Body starts:", response.text[:80])

Two habits worth copying forever: always pass timeout, and always call raise_for_status(). Without the timeout your script can hang indefinitely on a slow server. Without the status check, a 404 page gets parsed as if it were real data — the classic "my scraper returns empty results and I don't know why" bug.

Code Example #2 (Intermediate)

A polite, resilient session with retries and a real user agent.

import time
import requests

HEADERS = {
    "User-Agent": "MyResearchBot/1.0 (+https://example.com/about-my-bot)",
    "Accept": "text/html,application/json",
}

def fetch(url, attempts=3):
    """GET a URL, backing off and retrying on transient failures."""
    with requests.Session() as session:      # reuses the TCP connection
        session.headers.update(HEADERS)

        for attempt in range(1, attempts + 1):
            try:
                r = session.get(url, timeout=10)
            except requests.exceptions.RequestException as err:
                print(f"  attempt {attempt} failed: {err}")
            else:
                if r.status_code == 429:     # "too many requests"
                    wait = int(r.headers.get("Retry-After", 5))
                    print(f"  rate limited; sleeping {wait}s")
                    time.sleep(wait)
                    continue
                if r.ok:
                    return r
                if 400 <= r.status_code < 500:
                    return None              # our fault -- retrying won't help

            time.sleep(2 ** attempt)         # 2s, 4s, 8s -- exponential backoff

    return None

result = fetch("https://httpbin.org/json")
if result:
    print(result.json()["slideshow"]["title"])
else:
    print("Gave up after all attempts.")

The Session is the important upgrade. It keeps the TCP connection open across requests, remembers cookies, and applies your headers once instead of on every call — measurably faster when you are fetching a hundred pages.

Notice the distinction the retry loop makes: a 429 or 5xx is worth retrying, a 404 or 403 is not. Hammering a server that has already told you "no" is how scrapers get IP-banned.


Common Mistakes

  1. No timeout: requests.get(url) with no timeout can block forever. There is no default. Always pass one.
  2. Assuming 200: requests does not raise on a 404 — it hands you the error page as .text. Call raise_for_status() or check .ok.
  3. Using .text for binary files: decoding a JPEG as text corrupts it. Images, PDFs, and zips need .content written in "wb" mode.
  4. A new connection per request: calling requests.get() in a loop reopens a TCP connection every time. Use a Session.
  5. Sending the default user agent: python-requests/2.31.0 is the first thing blocklists match on. Identify your bot honestly instead.
  6. Calling .json() without checking: if the server returned HTML, .json() raises JSONDecodeError. Verify Content-Type first, or wrap it.

Best Practices

  • Always set a timeout: 10 seconds is a sane default; tune it per endpoint.
  • Use a Session for more than one request: connection reuse plus shared headers and cookies.
  • Back off exponentially: 2s, 4s, 8s. Retrying instantly just multiplies the load you already failed to handle.
  • Respect Retry-After: when a server tells you how long to wait, waiting exactly that long is the difference between a good citizen and a blocked IP.
  • Keep secrets out of URLs: send API keys in headers (Authorization: Bearer ...), not query strings — URLs end up in server logs.
  • Stream large downloads: requests.get(url, stream=True) plus iter_content() avoids loading a 2GB file into memory.

Practice Exercises

  1. The Status Checker: Given a list of five URLs, print each one's status code and response time, handling timeouts without crashing the loop.
  2. The JSON Client: Fetch https://httpbin.org/json, parse it with .json(), and pretty-print the nested structure. Then request a URL that returns HTML and handle the JSONDecodeError gracefully.
  3. The Resilient Downloader: Download an image using stream=True, write it in chunks to disk, and retry up to three times with exponential backoff if the connection drops.