01Introduction
Web scraping with Python means downloading a web page with requests and pulling the data out of its HTML with BeautifulSoup. For most pages that's about 20 lines of code: fetch the page, select the elements you want with CSS selectors, follow the "next" link, and save the results to a CSV file.
import requests
from bs4 import BeautifulSoup
html = requests.get("https://quotes.toscrape.com/", timeout=10).text
soup = BeautifulSoup(html, "html.parser")
for quote in soup.select("div.quote"):
print(quote.select_one("small.author").get_text(strip=True))This tutorial builds a complete Python scraper step by step, on Quotes to Scrape, a practice site made for scraping. Every output shown comes from running the code against that site's HTML in December 2026, with Python 3.13 and beautifulsoup4 4.15. Then it covers what breaks once you scrape real sites, and when calling an API is less work than owning a scraper.
02What you need
Python 3.9 or later and two libraries:
pip install requests beautifulsoup4- requests downloads the page over HTTP.
- BeautifulSoup (the
beautifulsoup4package) parses the HTML so you can find elements with CSS selectors.
03Step 1: Look at the HTML first
Before writing code, open the page in your browser, right-click the data you want and choose Inspect. On Quotes to Scrape, each quote looks like this:
<div class="quote">
<span class="text">“The world as we have created it is a process of our thinking. ...”</span>
<span>by <small class="author">Albert Einstein</small></span>
<div class="tags">
<a class="tag" href="/tag/change/page/1/">change</a>
<a class="tag" href="/tag/deep-thoughts/page/1/">deep-thoughts</a>
</div>
</div>That gives you three selectors: div.quote for each item, span.text and small.author inside it, and a.tag for the tags. Finding stable selectors is most of the work in Python web scraping.
04Step 2: Fetch the page
import requests
headers = {"User-Agent": "Mozilla/5.0 (compatible; quotes-tutorial/1.0)"}
response = requests.get("https://quotes.toscrape.com/", headers=headers, timeout=10)
response.raise_for_status() # stop on 4xx and 5xx errors
html = response.textAlways set a timeout, or a slow server can hang your script forever. raise_for_status() turns a 404 or 503 into an exception instead of letting you parse an error page.
05Step 3: Parse it with BeautifulSoup
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
quotes = []
for q in soup.select("div.quote"):
quotes.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")],
})
print(len(quotes))
print(quotes[0])Output:
10
{'text': '“The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.”', 'author': 'Albert Einstein', 'tags': ['change', 'deep-thoughts', 'thinking', 'world']}select() returns every match and select_one() returns the first. get_text(strip=True) removes the surrounding whitespace.
06Step 4: Follow the pages
Most sites split results across pages. Find the "next" link and keep going until it disappears:
next_link = soup.select_one("li.next a")
print(next_link["href"] if next_link else None)/page/2/Quotes to Scrape has 10 pages of 10 quotes. Page 10 has no "next" link, which is how the loop below knows to stop.
07Step 5: Put it together and save to CSV
Here's the complete Python scraper:
import csv
import time
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
BASE = "https://quotes.toscrape.com/"
HEADERS = {"User-Agent": "Mozilla/5.0 (compatible; quotes-tutorial/1.0)"}
session = requests.Session()
session.headers.update(HEADERS)
url = BASE
rows = []
while url:
response = session.get(url, timeout=10)
response.raise_for_status()
soup = BeautifulSoup(response.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": ", ".join(t.get_text(strip=True) for t in q.select("a.tag")),
})
next_link = soup.select_one("li.next a")
url = urljoin(BASE, next_link["href"]) if next_link else None
time.sleep(1) # be polite: one request per second
with open("quotes.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=["text", "author", "tags"])
writer.writeheader()
writer.writerows(rows)
print(f"Saved {len(rows)} quotes")We walked the site's pagination live: 10 pages with 10 quotes each, so the scraper saves 100 quotes and stops after page 10. A Session reuses the connection between requests, and urljoin turns the relative /page/2/ into a full URL.
08Scraping JavaScript pages with Python
Quotes to Scrape also has a JavaScript version at /js/. It looks identical in the browser. But when we downloaded its raw HTML, the way requests does, it contained zero div.quote elements. BeautifulSoup only sees the HTML the server sends, so the scraper above would save an empty file without any error.
The quotes are still in that HTML, inside a <script> tag:
<script>
var data = [
{
"tags": ["change", "deep-thoughts", "thinking", "world"],
"author": {"name": "Albert Einstein", ...},
"text": "\u201cThe world as we have created it ...\u201d"
},
...
];
</script>You have three ways to get them.
Option 1: Read the data from the page source
When the data is embedded in the page, pull it out directly. It's the fastest option and needs no browser:
import json
import re
import requests
html = requests.get("https://quotes.toscrape.com/js/", timeout=10).text
match = re.search(r"var data = (\[.*?\]);", html, re.DOTALL)
quotes = json.loads(match.group(1))
print(len(quotes))
print(quotes[0]["author"]["name"])10
Albert EinsteinOn other sites the data often comes from a separate JSON request instead. Open your browser's Network tab, filter by Fetch/XHR, and call that URL with requests. A JSON endpoint is easier to work with than HTML.
Option 2: Use a headless browser
If the data isn't in the source or a JSON request, let a real browser run the JavaScript first. With Playwright (pip install playwright, then playwright install chromium):
from 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 = [
{
"text": q.locator("span.text").inner_text(),
"author": q.locator("small.author").inner_text(),
}
for q in page.locator("div.quote").all()
]
browser.close()
print(len(quotes))This also prints 10. It works on almost any page, but each page load starts a browser, so it's slower and uses more memory. Selenium works the same way. See Playwright vs Puppeteer vs Selenium for how they compare.
Option 3: Use an extraction API
An API can render and clean the page for you, so you don't run browsers yourself. That's covered in the API section below.
09How to avoid getting blocked
Before you scrape a site, check its robots.txt. The format is standardized in RFC 9309, and Python reads it with the built-in urllib.robotparser:
from urllib import robotparser
rp = robotparser.RobotFileParser("https://quotes.toscrape.com/robots.txt")
rp.read()
print(rp.can_fetch("quotes-tutorial", "https://quotes.toscrape.com/page/2/"))Quotes to Scrape has no robots.txt (the URL returns 404), and robotparser treats a missing file as "allowed", so this prints True. On a site that disallows the path, it prints False, and your scraper should skip it.
Servers also fail or throttle you now and then. Instead of crashing on the first 429 or 503, let requests retry with a growing delay:
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
retry = Retry(
total=5,
backoff_factor=1, # waits longer after each failed attempt
status_forcelist=[429, 500, 502, 503, 504],
respect_retry_after_header=True,
)
session = requests.Session()
session.mount("https://", HTTPAdapter(max_retries=retry))Use this session in place of the one in Step 5. It honors the server's Retry-After header when there is one. If you still get 403 or 429 after slowing down, the site doesn't want automated traffic, and an official API or data provider is the better route.
10What breaks once you scrape real sites
Practice sites are friendly. Real ones change, block and throttle, and every scraper you write becomes code you maintain:
| What happens | What you end up owning |
|---|---|
| The site changes its HTML | Selectors that silently return nothing, and a fix each time |
| Content loads with JavaScript | A headless browser, more memory and slower runs |
You get blocked or rate-limited (403, 429) | Retries, delays, rotating proxies |
| CAPTCHAs and bot checks | Usually a sign to stop, or a third-party service |
| Every site is structured differently | One parser per site |
| Terms of service and the law | Checking each site before you scrape it |
Always check a site's terms before you scrape it, as well as its robots.txt. For the legal side, see Web Scraping in 2026: What Changed, What's Legal, and What to Use Instead.
11When to use an API instead of a scraper
Writing your own Python scraper is the right choice when you need specific fields from one or two sites you understand well, and you can fix it when the site changes.
An extraction API is often less work when:
- You need the main content of many different sites, such as articles, product pages or docs, and writing one parser per site doesn't scale.
- The pages are rendered with JavaScript and you don't want to run browsers.
- The text goes into an LLM or a RAG pipeline, where clean Markdown is more useful than raw HTML.
- You'd rather not maintain selectors every time a site changes.
With the AI-ready Clean Data Extractor API, the scraping step becomes one request from Python:
import os
import requests
response = requests.post(
"https://api.eu.apyhub.com/apyhub/webpage-extractor-api",
headers={"apy-token": os.environ["APY_TOKEN"], "Content-Type": "application/json"},
json={"url": "https://quotes.toscrape.com/"},
timeout=60,
)
page = response.json()["data"]
print(page["title"], page["page_type"])
print(page["clean_markdown"][:500])According to its documentation, the data object can include the page's title, summary, headings, sections, links, images, tables, page_type and the content as clean_markdown, plus a quality score. You get one structure for any page, with no selectors to write.
For specific jobs there are narrower APIs in the ApyHub catalog:
- Extract Text from Webpage API for the readable text of a page.
- Extract Sitemap from URL API to list every URL on a site before you crawl it.
- SERP Rank Checker API for Google results, instead of scraping Google yourself.
To compare tools that turn pages into LLM-ready Markdown, see Firecrawl Alternatives in 2026.
Try the AI-ready Clean Data Extractor API →
12Scraping with AI assistants
Every ApyHub endpoint is also available through ApyHub MCP. In Claude, ChatGPT, Cursor or another AI assistant, you can ask "extract the main content of this page as Markdown" and the assistant calls the extraction API instead of writing and debugging a scraper, which gives consistent results and uses fewer tokens. When you need the same extraction every day, move the call into your own Python code like the example above.
13Conclusion
Web scraping with Python takes two libraries: requests to fetch the page and BeautifulSoup to parse it. Inspect the HTML, pick stable selectors, follow the "next" links, sleep between requests and save to CSV. If the HTML comes back empty, the page is rendered with JavaScript, so look for the JSON source, use a headless browser or use an extraction API. Write your own scraper for a few sites you know well, and use an API when you need clean content from many sites without maintaining a parser for each.
Start free on ApyHub, no card required →
14FAQ
How do I scrape a website with Python?
Inspect the page to find CSS selectors for the data, download it with requests, parse it with BeautifulSoup, follow the "next" links and save the results to CSV, as in the complete scraper above. If the data is loaded with JavaScript, read it from the page source or use Playwright.
Is Python good for web scraping?
Yes. Python is the most common language for web scraping because requests, BeautifulSoup, Scrapy and Playwright cover everything from one page to large crawls, and the data drops straight into pandas or a database.
What is the best Python library for web scraping?
For static pages, requests with BeautifulSoup is the simplest. For large crawls across many pages, Scrapy handles scheduling, retries and pipelines. For pages rendered with JavaScript, use Playwright or Selenium.
Is BeautifulSoup or Scrapy better?
BeautifulSoup is a parser: you write the fetching and the loop yourself, which suits small scripts. Scrapy is a full crawling framework with its own scheduler and pipelines, which suits large or recurring crawls.
Why does my Python scraper return an empty list?
Usually the page builds its content with JavaScript, so the HTML that requests downloads doesn't contain it. Check the page source (not the Inspect view) for your data. It's often in a <script> tag you can parse as JSON. If it isn't there, find the JSON request the page makes, or use Playwright or an extraction API.
How do I avoid getting blocked when scraping?
Send a clear User-Agent, add a delay between requests, check robots.txt with urllib.robotparser, retry with backoff, and don't send requests in parallel to a small site. If you still get 403 or 429 responses, the site doesn't want automated traffic, and an official API or data provider is the better route.
Is web scraping legal?
It depends on the site's terms, the data and your country. Scraping public data is often allowed, but personal data, content behind logins and sites that forbid it carry legal risk. See our guide to web scraping in 2026.
How do I scrape a website with Python without writing a parser?
Send the URL to an extraction API such as the AI-ready Clean Data Extractor API, which returns the page's title, sections, links, tables and clean Markdown as JSON.
How can I test a scraping API before writing code?
Send the request with curl, use the "Try it" panel on the API's page, or save the request in Voiden or Postman and run it against the pages you want. You can also ask an AI assistant connected to ApyHub MCP to run it.
15About ApyHub
ApyHub runs a catalog of ready-made APIs and is the trusted operational layer between your application and the services it depends on, so your team builds and maintains less of its own code and ships faster. One subscription covers the whole catalog of over 1,500 endpoints and capabilities, and it keeps growing. Every service is verified before it is listed and carries machine-readable certification covering GDPR, SOC 2 and ISO 27001. Every endpoint is MCP-ready by default. ApyHub runs dedicated EU, US and India regions and serves more than 65,000 developer workspaces every month. Start on the free tier with no card, or publish your own API on ApyHub.
16Sources
- Quotes to Scrape, a practice site by Zyte: page structure, pagination (10 pages) and the JavaScript version at
/js/, checked December 2026 - Beautiful Soup documentation
- Requests documentation
- Playwright for Python documentation
- IETF, RFC 9309: Robots Exclusion Protocol
- ApyHub, AI-ready Clean Data Extractor API documentation