Dev tools
Web Scraping With Python: A Beginner's Guide
Web scraping with Python, step by step: Requests and Beautiful Soup, pagination, CSV export, JavaScript pages with Playwright, Scrapy and polite scraping.
Web scraping with Python means writing a script that downloads web pages and pulls out the data you need, such as prices, titles or links, so you don't have to copy it by hand. For most pages, two libraries do the job: Requests fetches the HTML and Beautiful Soup lets you find elements in it with CSS selectors. For pages that build their content with JavaScript, you drive a real browser with Playwright or Selenium, and for large crawls you use the Scrapy framework.
This beginner's guide explains what is web scraping in Python, walks through a complete Python web scraping example on a practice site built for scraping, covers pagination and saving to CSV, compares the best web scraping Python library for each kind of job, and ends with the rules for scraping politely and legally.
What Is Web Scraping in Python?
Web scraping is the automated collection of data from websites. A scraper does what you do in a browser, request a page and read it, but in code, so it can repeat the job across hundreds or thousands of pages.
Python is the most popular language for it because of its libraries. Every scraper has the same three steps:
- Fetch the page: send an HTTP request and get the HTML back.
- Parse the HTML: turn the text into a tree you can search, then pick out the elements you want.
- Store the results: write them to a CSV file, a spreadsheet, a database or JSON.
Before you scrape anything, check whether the site offers an API. An official API gives you clean, structured data with documented limits, and it's more stable than parsing HTML that can change any day. Scrape when there's no API, or when the API doesn't expose what you need.
The Best Web Scraping Python Library for Each Job
There's no single best web scraping Python library; each one fits a different kind of page and project size. Here's how the main options compare:
| Library | What it does | Runs JavaScript | Speed | Learning curve | Use it when |
|---|---|---|---|---|---|
| Requests | Sends HTTP requests | No | Fast | Easy | Fetching static pages and APIs |
| HTTPX | HTTP client with async and HTTP/2 support | No | Fast; concurrent with async | Easy | Many requests in parallel |
| Beautiful Soup | Parses HTML; find elements by tag, class or CSS selector | No | Moderate (faster with lxml) | Easy | Extracting data from fetched HTML |
| lxml | Fast HTML/XML parser with XPath | No | Very fast | Medium | Large documents, XPath queries |
| Playwright | Controls Chromium, Firefox and WebKit | Yes | Slower (full browser) | Medium | JavaScript-heavy pages, logins, clicking |
| Selenium | Controls real browsers via WebDriver | Yes | Slower (full browser) | Medium | Existing Selenium setups, browser testing |
| Scrapy | Full crawling framework: scheduling, retries, pipelines, exports | Not by default | Fast; concurrent | Steeper | Crawling many pages or whole sites |
The usual path: start with Requests and Beautiful Soup, move to Playwright if the data only appears after JavaScript runs, and move to Scrapy when your script grows into a crawler with many pages, retries and exports. Our comparison of Playwright vs Selenium covers the browser tools in depth.
Set Up Your Environment for Web Scraping With Python
You need Python 3 and three packages. Create a virtual environment first so the packages stay with your project:
python3 -m venv .venv
source .venv/bin/activate
pip install requests beautifulsoup4 lxmlOn Windows, activate with .venv\Scripts\activate instead. The package is called beautifulsoup4; the older BeautifulSoup package is Beautiful Soup 3 and shouldn't be used for new code. If you'd rather use a faster installer, our guide to uv vs pip shows the uv equivalents.
Step 1: Inspect the Page
The examples below use books.toscrape.com, a fake bookstore made for scraping practice, with 1,000 books spread across 50 pages of 20.
Open the page in your browser, right-click a book and choose Inspect. In the developer tools you'll see the structure that matters:
- Each book sits in an
<article class="product_pod">element. - The full title is in the
titleattribute of the link inside<h3>; the visible link text is shortened. - The price is in
<p class="price_color">. - Stock status is in
<p class="instock availability">. - The link to the next page is in
<li class="next">.
This step matters more than any code: a scraper is only as good as the selectors you pick. Prefer stable class names and attributes over long paths like div > div > ul > li:nth-child(3), which break the moment the layout shifts.
Step 2: Fetch the HTML With Requests
import requests
URL = "https://books.toscrape.com/"
HEADERS = {"User-Agent": "book-research-script/1.0 (contact: [email protected])"}
response = requests.get(URL, headers=HEADERS, timeout=10)
response.raise_for_status()
print(response.status_code, len(response.content))Three habits from the start:
- Always set a timeout. The Requests documentation says that if no timeout is given, requests don't time out, and a stalled server can hang your script indefinitely.
- Call `raise_for_status()`. It raises an error on 4xx and 5xx responses instead of letting you parse an error page.
- Identify yourself. A descriptive User-Agent with contact details is polite and helps site owners reach you instead of blocking you.
Step 3: Parse It With Beautiful Soup
Now the web scraping with Python and BeautifulSoup part. Pass the downloaded bytes to Beautiful Soup and pick a parser:
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.content, "lxml")
books = []
for card in soup.select("article.product_pod"):
link = card.select_one("h3 a")
books.append({
"title": link.get("title"),
"price": card.select_one("p.price_color").get_text(strip=True),
"in_stock": "In stock" in card.select_one("p.availability").get_text(),
"url": link.get("href"),
})
print(len(books), books[0])The key methods:
select()returns every element that matches a CSS selector;select_one()returns the first match orNone.get_text(strip=True)returns the element's text without surrounding whitespace.tag.get("href")reads an attribute and returnsNoneif it's missing, which is safer thantag["href"].
A real encoding trap. This site sends Content-Type: text/html with no character set. When that happens, Requests falls back to ISO-8859-1 for response.text, so the pound sign comes out as £51.77. Passing response.content (raw bytes) instead lets Beautiful Soup read the page's own <meta charset="UTF-8"> tag and decode it correctly. If you see odd characters like  or ’ in scraped text, check the encoding before anything else.
Step 4: Follow Pagination
One page has 20 books. To get all 1,000, follow the "next" link until there isn't one. Relative links need to be joined to the current URL, which urljoin handles:
import time
from urllib.parse import urljoin
def scrape_all(start_url):
url, rows = start_url, []
with requests.Session() as session:
session.headers.update(HEADERS)
while url:
r = session.get(url, timeout=10)
r.raise_for_status()
soup = BeautifulSoup(r.content, "lxml")
for card in soup.select("article.product_pod"):
link = card.select_one("h3 a")
price = card.select_one("p.price_color").get_text(strip=True)
rows.append({
"title": link.get("title"),
"price_gbp": float(price.lstrip("£")),
"url": urljoin(url, link.get("href")),
})
nxt = soup.select_one("li.next a")
url = urljoin(url, nxt.get("href")) if nxt else None
time.sleep(1) # be polite: one request per second
return rowsWhy urljoin matters here: on the home page the next link is catalogue/page-2.html, but on page 2 it's just page-3.html, relative to the catalogue/ folder. Gluing strings together by hand breaks on exactly this kind of difference.
A Session reuses the connection between requests, which is faster and gentler on the server than opening a new connection for every page.
Step 5: Save the Data to CSV
import csv
rows = scrape_all("https://books.toscrape.com/")
with open("books.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["title", "price_gbp", "url"])
writer.writeheader()
writer.writerows(rows)
print(f"Saved {len(rows)} books")If you work with pandas, pandas.DataFrame(rows).to_csv("books.csv", index=False) does the same in one line and gives you sorting and filtering for free.
Handle Errors and Retries
Real sites fail now and then: a request times out, the server returns 503 while it's busy, or a rate limiter answers 429. A scraper that crashes on the first error loses everything it collected. Two fixes cover most cases.
Retry with backoff. Requests can hand retries to urllib3's Retry class through an adapter mounted on your session:
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
retry = Retry(total=5, backoff_factor=1, status_forcelist=[429, 500, 502, 503, 504])
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))With backoff_factor=1, urllib3 waits longer after each failed attempt, following the formula in its documentation (backoff factor × 2 to the power of previous retries), capped at 120 seconds by default. It also honors a Retry-After header by default, so when a server says "come back in 30 seconds," your scraper does. By default it only retries idempotent methods such as GET, which is what scraping uses.
Save as you go. For long runs, write each page's rows to the file as soon as you have them, or record the last page you finished. If the script stops at page 37 of 50, you restart from 37 instead of from scratch.
Validate what you extract. A selector that silently returns None on a changed page produces a CSV full of blanks. Count the items per page and log a warning when a page returns zero results or a required field is missing, so you notice a layout change the day it happens.
Python Web Scraping Example: What the Full Run Costs
Here's what the complete Python web scraping example above does, worked out from the site's structure and the code's settings:
| Item | Value |
|---|---|
| Books on the site | 1,000 |
| Books per listing page | 20 |
| Listing pages requested | 50 |
| Delay between requests | 1 second |
| Minimum run time from delays alone | about 50 seconds, plus download time |
| Requests if you also opened every book's detail page | 50 + 1,000 = 1,050 |
| Minimum run time for that at 1 request per second | about 17.5 minutes |
That last line is the lesson: scraping detail pages multiplies the request count. Before crawling deeper, check whether the listing pages already carry what you need. Here they have title, price and stock status, so 50 requests are enough instead of 1,050.
Scraping JavaScript Pages With Playwright
Some sites send an almost empty HTML page and build the content with JavaScript in the browser. Requests only sees that empty shell. You can spot this when the data is visible in the browser but missing from response.text.
First, open the browser's developer tools, go to the Network tab and reload. Many JavaScript sites load their data from a JSON API; if you find that request, you can call it directly with Requests, which is far faster than running a browser.
If there's no usable API, drive a real browser. With Playwright:
pip install playwright
playwright installfrom playwright.sync_api import sync_playwright
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto("https://quotes.toscrape.com/js/")
page.wait_for_selector("div.quote")
quotes = page.locator("div.quote span.text").all_inner_texts()
browser.close()
print(len(quotes), quotes[0])The /js/ version of the quotes practice site writes its quotes with JavaScript, so this is a fair test. playwright install downloads the browser binaries; wait_for_selector waits until the quotes exist before reading them. Browser scraping is slower and heavier, so use it only for the pages that need it.
Scaling Up With Scrapy
When a script turns into a crawler, with many pages, retries, throttling, deduplication and exports, Scrapy handles that plumbing for you. A spider for the quotes site, following the pattern in Scrapy's tutorial:
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = ["https://quotes.toscrape.com/"]
def parse(self, response):
for q in response.css("div.quote"):
yield {
"text": q.css("span.text::text").get(),
"author": q.css("small.author::text").get(),
}
next_page = response.css("li.next a::attr(href)").get()
if next_page:
yield response.follow(next_page, self.parse)Inside a project created with scrapy startproject, run it with scrapy crawl quotes -O quotes.json. The -O flag overwrites the output file; -o appends, which can produce invalid JSON, so use JSON Lines if you append. Scrapy also reads robots.txt by default in new projects and has an AutoThrottle extension that adapts the crawl speed to the server.
Web Scraping With Python and AI
Large language models have added a new option for the parsing step. Instead of writing a selector for every field, you can pass a page's cleaned text to a model and ask it to return structured JSON, for example "title, price, author and publication date." That helps when you scrape many differently built sites, such as hundreds of small shops, where writing selectors for each one isn't practical.
The trade-offs are real, though. Each page costs tokens, so it's slower and more expensive than a CSS selector at scale. Models can misread or invent a value, so you still need validation. And the fetching, politeness and legal rules stay exactly the same. A practical pattern is to use selectors for the sites you scrape often and an LLM for the long tail, checking its output against a schema.
How to Scrape Politely
A scraper that hammers a site can slow it down for real users and get your IP blocked. Good manners also keep you on the right side of most site owners.
- Read robots.txt. It tells crawlers which paths to avoid. Python's standard library can check it:
from urllib.robotparser import RobotFileParser
rp = RobotFileParser()
rp.set_url("https://example.com/robots.txt")
rp.read()
print(rp.can_fetch("book-research-script", "https://example.com/catalogue/"))
print(rp.crawl_delay("book-research-script"))- Slow down. One request per second is a common courtesy default; respect any
Crawl-delaythe site sets. - Handle 429 and 503 responses. They mean "too many requests" or "overloaded": back off and retry later instead of retrying instantly. Our guide to API rate limiting explains backoff with jitter.
- Cache what you download. Save raw HTML while developing so you don't re-fetch the same pages every time you fix a selector.
- Scrape off-peak for large jobs, and stop if the site asks you to.
Is Web Scraping Legal?
It depends on what you scrape, how, and where you are, so treat this as general information, not legal advice.
- Public data is treated differently from data behind a login. In the US case hiQ Labs v. LinkedIn, the Ninth Circuit reasoned in 2022 that the federal anti-hacking law (the CFAA) doesn't reach publicly available web pages. But the same case later found hiQ had breached LinkedIn's user agreement, and it ended in a settlement against hiQ, so contracts and terms of service still matter.
- Personal data brings privacy law. Scraping names, emails or profiles of people can fall under laws like the EU's GDPR, even when the pages are public.
- Copyright still applies to the content you collect; facts like prices are treated differently from articles, photos or reviews.
- Don't bypass access controls, such as logins you don't have permission to use, paywalls or CAPTCHAs.
When in doubt, use the site's API, ask for permission or get legal advice for your situation.
Common Mistakes
- No timeout. One stalled request freezes the whole script.
- Parsing `response.text` blindly. Wrong encoding guesses garble text; pass
response.contentto Beautiful Soup. - Brittle selectors. Long positional paths break with any layout change; anchor on classes, IDs and attributes.
- Building URLs by string concatenation. Use
urljoinfor relative links. - Assuming every page has every element.
select_one()returnsNonewhen nothing matches; check before calling.get_text(). - Starting with a browser. Playwright and Selenium are slow; check for a JSON API or static HTML first.
- Scraping when an API exists. It's more work and less reliable.
FAQ
Is Python good for web scraping?
Yes. Python has mature libraries for every step, from Requests and Beautiful Soup for simple pages to Playwright for JavaScript sites and Scrapy for large crawls, plus pandas for cleaning the data afterwards.
What is the best Python library for web scraping?
For beginners and static pages, Requests plus Beautiful Soup. For pages built with JavaScript, Playwright. For crawling many pages with retries and exports, Scrapy.
Is Beautiful Soup or Selenium better?
They do different jobs. Beautiful Soup parses HTML you already have; it can't run JavaScript or click buttons. Selenium (or Playwright) controls a browser, so it can load dynamic pages, but it's much slower. Many scrapers use a browser only to load the page, then parse the HTML with Beautiful Soup.
How do I scrape a website that uses JavaScript?
First look in the browser's Network tab for the JSON request that loads the data, and call it directly. If there isn't one, use Playwright or Selenium to render the page, wait for the elements to appear, then extract them.
Can websites detect web scraping?
Yes. Sites see request rates, headers and behavior, and many use bot detection. Scraping slowly, identifying your script, respecting robots.txt and using official APIs where they exist avoids most problems.