Python web scraping
last modified November 29, 2026 Python 3.15
In this article we show how to do web scraping in Python. We fetch pages with
the requests library and extract data with BeautifulSoup and
lxml.
Web scraping is fetching web pages and extracting data from them with a program. It is used to collect prices, job listings, articles, or any other data that a site publishes as HTML but not through an API. A scraper has two parts: an HTTP client that downloads the page, and a parser that turns the HTML into a tree of elements that we can search.
The examples use example.com, httpbin.org, and
quotes.toscrape.com. The last one is a sandbox site built for
practising web scraping; it has quotes with authors and tags, pagination,
and a JavaScript version of the same data. Scrape real sites only when their
terms allow it and keep the request rate low. We install the libraries with
pip, preferably in a virtual
environment.
$ pip install requests beautifulsoup4 lxml
Fetching a page
The first step is downloading the HTML document. The Requests library does this with a single function call.
import requests
resp = requests.get('https://example.com', timeout=10)
print(resp.status_code)
print(resp.headers['Content-Type'])
print(len(resp.text))
print(resp.text[:63])
The program downloads the home page of example.com and prints
some details of the response.
resp = requests.get('https://example.com', timeout=10)
The get function sends a GET request and returns a
Response object. Always set a timeout; without it, the program
can wait forever on a server that does not answer.
print(resp.status_code) print(resp.headers['Content-Type'])
Status code 200 means success. The Content-Type header tells us
that the body is an HTML document encoded in UTF-8.
print(len(resp.text)) print(resp.text[:63])
The text attribute holds the decoded body as a string. At this
point it is only text; to get the data out of it, we need a parser.
$ python fetch_page.py 200 text/html; charset=utf-8 577 <!doctype html><html lang=en><head><meta charset=utf-8><link re
Parsing the page
BeautifulSoup builds a tree of Python objects from the HTML text. Tags are available as attributes of the tree.
import requests
from bs4 import BeautifulSoup
resp = requests.get('https://example.com', timeout=10)
soup = BeautifulSoup(resp.text, 'html.parser')
print(soup.title.string)
print(soup.p.get_text())
print(soup.html['lang'])
The program prints the title of the page, the text of its paragraph, and the language of the document.
soup = BeautifulSoup(resp.text, 'html.parser')
The second argument selects the parser. The html.parser parser
is part of the standard library; lxml is faster and can be used
instead when it is installed.
print(soup.title.string) print(soup.p.get_text()) print(soup.html['lang'])
The soup.title and soup.p expressions return the
first title and p tag of the document. Attributes
of a tag are read with the subscript operator.
$ python page_title.py Example Domain This domain is for use in documentation examples without needing permission. This is not a service; avoid relying on it for testing and monitoring purposes. en
Finding an element
Real pages contain many elements of the same kind; we distinguish them by
their classes. On quotes.toscrape.com, every quote is a
div with the quote class, containing a
span with the text and a small tag with the author.
import requests
from bs4 import BeautifulSoup
url = 'https://quotes.toscrape.com/'
resp = requests.get(url, timeout=10)
soup = BeautifulSoup(resp.text, 'html.parser')
quote = soup.find('div', class_='quote')
text = quote.find('span', class_='text').get_text()
author = quote.find('small', class_='author').get_text()
print(text)
print('--', author)
The program prints the first quote on the page and its author.
quote = soup.find('div', class_='quote')
The find method returns the first element that matches the tag
name and attributes. The keyword is class_ because
class is a reserved word in Python.
text = quote.find('span', class_='text').get_text()
author = quote.find('small', class_='author').get_text()
We search inside the found element, so we get the text and author of that quote and not of some other one.
$ python first_quote.py “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.” -- Albert Einstein
Extracting all items
CSS selectors are a shorter way to describe what we want. The
select method returns all matching elements and
select_one the first one.
import requests
from bs4 import BeautifulSoup
url = 'https://quotes.toscrape.com/'
resp = requests.get(url, timeout=10)
soup = BeautifulSoup(resp.text, 'html.parser')
quotes = soup.select('div.quote')
print(f'{len(quotes)} quotes on the page')
for quote in quotes[:4]:
author = quote.select_one('small.author').get_text()
tags = [a.get_text() for a in quote.select('a.tag')]
text = quote.select_one('span.text').get_text()
print(f'{author}: {text[:40]}...')
print(' tags:', ', '.join(tags))
The program counts the quotes on the page and prints the author, the start of the text, and the tags of the first four quotes.
quotes = soup.select('div.quote')
The div.quote selector matches div elements with
the quote class. The result is a list.
tags = [a.get_text() for a in quote.select('a.tag')]
A quote can have several tags, so we use select and collect the
texts of the links into a list.
$ python all_quotes.py 10 quotes on the page Albert Einstein: “The world as we have created it is a pr... tags: change, deep-thoughts, thinking, world J.K. Rowling: “It is our choices, Harry, that show wha... tags: abilities, choices Albert Einstein: “There are only two ways to live your li... tags: inspirational, life, live, miracle, miracles Jane Austen: “The person, be it gentleman or lady, wh... tags: aliteracy, books, classic, humor
Using lxml and XPath
The lxml library offers XPath, a query language that can select elements and their text in one expression.
import requests
from lxml import html
url = 'https://quotes.toscrape.com/'
resp = requests.get(url, timeout=10)
root = html.fromstring(resp.content)
for quote in root.xpath('//div[@class="quote"]')[:4]:
author = quote.xpath('.//small[@class="author"]/text()')[0]
tags = quote.xpath('.//a[@class="tag"]/text()')
print(f'{author:20} {len(tags)} tags')
authors = root.xpath('//small[@class="author"]/text()')
print(len(set(authors)), 'distinct authors')
The program prints the authors and the number of tags of the first four quotes, and the number of distinct authors on the page.
root = html.fromstring(resp.content)
We pass the raw bytes in resp.content to lxml; it reads the
encoding from the document itself.
author = quote.xpath('.//small[@class="author"]/text()')[0]
tags = quote.xpath('.//a[@class="tag"]/text()')
An XPath query always returns a list. The leading dot makes the search
relative to the current quote, and the text() step returns the
text nodes instead of the elements.
authors = root.xpath('//small[@class="author"]/text()')
print(len(set(authors)), 'distinct authors')
The same query without the dot searches the whole document. A set removes the duplicate names.
$ python xpath_quotes.py Albert Einstein 4 tags J.K. Rowling 2 tags Albert Einstein 5 tags Jane Austen 4 tags 8 distinct authors
Setting the User-Agent
Every request carries a User-Agent header that identifies the
client. The httpbin.org/user-agent endpoint sends it back to
us.
import requests
url = 'https://httpbin.org/user-agent'
resp = requests.get(url, timeout=10)
print(resp.json())
headers = {'User-Agent': 'quote-collector/1.0 (+https://example.com/bot)'}
resp = requests.get(url, headers=headers, timeout=10)
print(resp.json())
The program sends two requests: the first with the default header, the second with our own.
headers = {'User-Agent': 'quote-collector/1.0 (+https://example.com/bot)'}
resp = requests.get(url, headers=headers, timeout=10)
Some sites block the default python-requests agent. A
descriptive name with a contact URL tells the site owner who is scraping
and how to reach us.
$ python user_agent.py
{'user-agent': 'python-requests/2.34.2'}
{'user-agent': 'quote-collector/1.0 (+https://example.com/bot)'}
Handling errors
Requests does not raise an exception for error status codes such as 404. We
have to check the status ourselves, or call
raise_for_status.
import requests
urls = [
'https://quotes.toscrape.com/',
'https://httpbin.org/status/404',
'https://httpbin.org/delay/5',
]
for url in urls:
try:
resp = requests.get(url, timeout=2)
resp.raise_for_status()
print(url, 'OK', len(resp.text))
except requests.HTTPError as e:
print(url, 'HTTP error', e.response.status_code)
except requests.Timeout:
print(url, 'timed out')
The program requests a working page, a page that returns 404, and a page that answers after five seconds.
resp = requests.get(url, timeout=2) resp.raise_for_status()
The raise_for_status method raises HTTPError for
4xx and 5xx responses. The two-second timeout raises Timeout
for the slow page.
except requests.HTTPError as e:
print(url, 'HTTP error', e.response.status_code)
The exception carries the response, so we can report the status code. A scraper that skips failed pages can keep going instead of crashing on the first error.
$ python http_errors.py https://quotes.toscrape.com/ OK 11021 https://httpbin.org/status/404 HTTP error 404 https://httpbin.org/delay/5 timed out
Respecting robots.txt
The robots.txt file tells crawlers which paths they should not
visit. The urllib.robotparser module from the standard library
reads it and answers whether a URL may be fetched.
from urllib.robotparser import RobotFileParser
rp = RobotFileParser('https://httpbin.org/robots.txt')
rp.read()
agent = 'quote-collector'
for path in ['/html', '/deny', '/user-agent']:
url = 'https://httpbin.org' + path
print(f'{url:32} {rp.can_fetch(agent, url)}')
The robots.txt file of httpbin.org disallows the
/deny path for all agents.
rp = RobotFileParser('https://httpbin.org/robots.txt')
rp.read()
The read method downloads and parses the file. If the file does
not exist, the parser allows everything.
print(f'{url:32} {rp.can_fetch(agent, url)}')
The can_fetch method checks a URL against the rules for the
given agent.
$ python robots_check.py https://httpbin.org/html True https://httpbin.org/deny False https://httpbin.org/user-agent True
Following pagination
Data is often split across many pages, each with a link to the next one. We find the link, turn it into an absolute URL, and repeat.
import time
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
session = requests.Session()
session.headers['User-Agent'] = 'quote-collector/1.0'
url = 'https://quotes.toscrape.com/'
max_pages = 3
for _ in range(max_pages):
resp = session.get(url, timeout=10)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, 'html.parser')
authors = [e.get_text() for e in soup.select('small.author')]
print(f'{url}: {len(authors)} quotes, first by {authors[0]}')
link = soup.select_one('li.next a')
if link is None:
break
url = urljoin(url, link['href'])
time.sleep(1)
The program walks through the first three pages of quotes.
session = requests.Session() session.headers['User-Agent'] = 'quote-collector/1.0'
A Session reuses the connection to the server and sends the
same headers with every request.
link = soup.select_one('li.next a')
if link is None:
break
url = urljoin(url, link['href'])
time.sleep(1)
The href attribute holds a relative path such as
/page/2/; urljoin resolves it against the current
URL. When there is no Next link, we are on the last page. The
one-second pause keeps the load on the server low.
$ python follow_pages.py https://quotes.toscrape.com/: 10 quotes, first by Albert Einstein https://quotes.toscrape.com/page/2/: 10 quotes, first by Marilyn Monroe https://quotes.toscrape.com/page/3/: 10 quotes, first by Pablo Neruda
Saving data to CSV
A scraper usually stores what it collects. In this example, we follow all
pages of the humor tag and write the quotes to a
CSV file.
import csv
import time
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
def parse_quotes(soup):
for quote in soup.select('div.quote'):
yield {
'author': quote.select_one('small.author').get_text(),
'text': quote.select_one('span.text').get_text().strip('“”'),
'tags': ' '.join(a.get_text() for a in quote.select('a.tag')),
}
session = requests.Session()
session.headers['User-Agent'] = 'quote-collector/1.0'
url = 'https://quotes.toscrape.com/tag/humor/'
rows = []
while url:
resp = session.get(url, timeout=10)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, 'html.parser')
rows.extend(parse_quotes(soup))
link = soup.select_one('li.next a')
url = urljoin(url, link['href']) if link else None
time.sleep(1)
with open('humor.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=['author', 'text', 'tags'])
writer.writeheader()
writer.writerows(rows)
print(len(rows), 'quotes saved to humor.csv')
The parsing is moved into a generator function, so the loop only deals with downloading pages.
def parse_quotes(soup):
for quote in soup.select('div.quote'):
yield {
'author': quote.select_one('small.author').get_text(),
'text': quote.select_one('span.text').get_text().strip('“”'),
'tags': ' '.join(a.get_text() for a in quote.select('a.tag')),
}
Each quote becomes a dictionary. We strip the typographic quotation marks from the text and join the tags into one string.
url = urljoin(url, link['href']) if link else None
The loop runs while there is a URL; after the last page it becomes
None.
writer = csv.DictWriter(f, fieldnames=['author', 'text', 'tags']) writer.writeheader() writer.writerows(rows)
The DictWriter writes the dictionaries as rows; fields that
contain commas are quoted automatically.
$ python quotes_csv.py 12 quotes saved to humor.csv $ head -3 humor.csv author,text,tags Jane Austen,"The person, be it gentleman or lady, who has not pleasure in a good novel, must be intolerably stupid.",aliteracy books classic humor Steve Martin,"A day without sunshine is like, you know, night.",humor obvious simile
JavaScript pages
Some pages build their content with JavaScript in the browser. Requests
only downloads the HTML; it does not run scripts. The
quotes.toscrape.com/js/ page shows the same quotes as the home
page, but creates them with JavaScript.
import requests
from bs4 import BeautifulSoup
for url in ['https://quotes.toscrape.com/', 'https://quotes.toscrape.com/js/']:
resp = requests.get(url, timeout=10)
soup = BeautifulSoup(resp.text, 'html.parser')
print(url, len(soup.select('div.quote')), 'quotes')
We count the quotes in both versions of the page.
print(url, len(soup.select('div.quote')), 'quotes')
The HTML of the JavaScript version contains no quote elements; they appear only after the script runs in a browser.
$ python js_requests.py https://quotes.toscrape.com/ 10 quotes https://quotes.toscrape.com/js/ 0 quotes
Rendering with Playwright
Playwright drives a real browser, which
runs the scripts. We install the library with pip install
playwright and then download a browser build with 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/')
quotes = page.locator('div.quote')
print(quotes.count(), 'quotes')
for i in range(3):
author = quotes.nth(i).locator('small.author').text_content()
print(author)
browser.close()
The program opens the JavaScript page in headless Chromium and reads the quotes from the rendered page.
page.goto('https://quotes.toscrape.com/js/')
The goto method waits until the page is loaded, and the inline
script has run by then.
quotes = page.locator('div.quote')
print(quotes.count(), 'quotes')
A locator finds elements in the live page with the same CSS selector we
used with BeautifulSoup. The nth method picks one of them.
$ python js_playwright.py 10 quotes Albert Einstein J.K. Rowling Albert Einstein
Data in scripts
A browser is slow and heavy. Before using one, look at the page source: the
data is often in the HTML already, inside a script. The JavaScript page
keeps its quotes in a var data = [...] array, which is valid
JSON.
import json
import re
import requests
resp = requests.get('https://quotes.toscrape.com/js/', timeout=10)
m = re.search(r'var data = (\[.*?\]);', resp.text, re.DOTALL)
data = json.loads(m.group(1))
print(len(data), 'quotes')
for item in data[:3]:
print(item['author']['name'], item['tags'])
The program extracts the array with a regular expression and parses it with
the json module.
m = re.search(r'var data = (\[.*?\]);', resp.text, re.DOTALL) data = json.loads(m.group(1))
The group captures the array literal; re.DOTALL lets the dot
match newlines, because the array spans many lines. The result is a list of
dictionaries, cleaner than any HTML.
print(item['author']['name'], item['tags'])
We read the fields directly, without any selectors.
$ python js_data.py 10 quotes Albert Einstein ['change', 'deep-thoughts', 'thinking', 'world'] J.K. Rowling ['abilities', 'choices'] Albert Einstein ['inspirational', 'life', 'live', 'miracle', 'miracles']
Source
Requests documentation
Beautiful Soup documentation
lxml.html documentation
urllib.robotparser module
Playwright for Python
In this article we have scraped web pages in Python. We have fetched pages
with Requests, extracted data with BeautifulSoup and lxml, set the
User-Agent, handled errors, checked robots.txt, followed
pagination, saved the data to CSV, and dealt with JavaScript pages. A
complete project that scrapes a bookstore is in
web scraping with
BeautifulSoup; the library itself is covered in
BeautifulSoup, and other parsers in
lxml and pyquery.
Author
List all Python tutorials.