BeautifulSoup tutorial: find, select and parse HTML for scraping
By the ProxyOnly team · 16 Nov 2026 · 5 min read
A tested BeautifulSoup tutorial: find, find_all and select, text and attributes, a complete scraper with pagination and CSV output, the encoding trap that garbles prices, and which parser to use.
BeautifulSoup is a Python library that turns HTML into a tree you can search. It does not download pages, so it is almost always paired with an HTTP library such as Requests. This tutorial covers the calls you will use every day, a complete scraper with pagination and CSV output, one encoding trap that garbles text without any error, and which parser to choose.
We ran everything on 16 November 2026 with beautifulsoup4 4.15.0 and Requests 2.34.2 on Python 3.10, against books.toscrape.com, a site built for scraping practice. The output shown is what it printed.
Install
pip install beautifulsoup4 requests lxmllxml is optional. It is a faster parser that BeautifulSoup can use, and it repairs broken HTML differently, as shown near the end.
The calls you will use most
These examples run against a small piece of HTML so that you can see exactly what each call returns.
from bs4 import BeautifulSoup
html = '<div class="card"><h2 id="t">Coffee <small>500 g</small></h2><a href="/p/1" class="buy now">Buy</a><a href="/p/2">More</a><p>Price: <b>$9.99</b></p></div>'
soup = BeautifulSoup(html, "html.parser")What each call returned:
soup.find("h2")returns the first match:<h2 id="t">Coffee <small>500 g</small></h2>.soup.find("h2").get_text(" ", strip=True)returns all the text inside it:Coffee 500 g.soup.h2.stringreturnsNone, because.stringonly works when a tag holds exactly one piece of text. Useget_text()instead.[a["href"] for a in soup.find_all("a")]returns every link:['/p/1', '/p/2'].soup.find("a", class_="buy")matches a tag that hasbuyamong its classes, and["class"]returns the list['buy', 'now'].soup.select_one("a.buy.now")["href"]uses a CSS selector and returns/p/1.soup.select("a[href^='/p/']")[1].get_text()selects by the start of an attribute and returnsMore.soup.find("b").find_parent("p").namewalks up the tree and returnsp.soup.find("a", href=lambda h: h and h.endswith("2"))filters with your own function.soup.find("span")andsoup.select_one("span")both returnNonewhen nothing matches, so check before you index into the result.
find and find_all search by tag name and attributes, and select and select_one take CSS selectors. Both styles work, and most people settle on CSS selectors because the same selector works in the browser's developer tools. Our XPath and CSS selector cheat sheet lists the common patterns.
A complete scraper
This collects the title, price, rating, stock status and link of every book on the first three pages, follows the "next" link, waits a second between pages and writes a CSV file.
import csv
import time
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
RATINGS = {"One": 1, "Two": 2, "Three": 3, "Four": 4, "Five": 5}
session = requests.Session()
session.headers["User-Agent"] = "bs4-tutorial/1.0 (+https://proxyonly.com/blog)"
url = "https://books.toscrape.com/catalogue/page-1.html"
rows = []
for _ in range(3):
response = session.get(url, timeout=20)
response.raise_for_status()
soup = BeautifulSoup(response.content, "html.parser")
for book in soup.select("article.product_pod"):
link = book.select_one("h3 a")
rows.append({
"title": link["title"],
"price": book.select_one("p.price_color").get_text(strip=True),
"rating": RATINGS[book.select_one("p.star-rating")["class"][1]],
"in_stock": "In stock" in book.select_one("p.availability").get_text(),
"url": urljoin(url, link["href"]),
})
next_link = soup.select_one("li.next a")
if not next_link:
break
url = urljoin(url, next_link["href"])
time.sleep(1)
with open("books.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=rows[0].keys())
writer.writeheader()
writer.writerows(rows)
print(len(rows), "books")
print(rows[0])60 books
{'title': 'A Light in the Attic', 'price': '£51.77', 'rating': 3, 'in_stock': True, 'url': 'https://books.toscrape.com/catalogue/a-light-in-the-attic_1000/index.html'}A few details carry the weight here. The short title on the page is cut off, so the full one comes from the link's title attribute. The rating is only in a class name, star-rating Three, so the second class is mapped to a number. Links on the page are relative, and urljoin turns them into full addresses based on the page they came from.
The encoding trap
Our first run printed the price as £51.77, with no error. The server sends Content-Type: text/html without a character set, so Requests fell back to ISO-8859-1 and decoded the page's UTF-8 bytes wrongly.
requests guessed encoding: ISO-8859-1
from r.text: £51.77
from r.content: £51.77Passing response.content, the raw bytes, lets BeautifulSoup read the character set that the page declares in its own HTML, and the pound sign came out right. Alternatively, set response.encoding = "utf-8" before reading response.text when you know the site's encoding. Check a few values by eye on any new site, because this kind of damage reaches your data quietly.
Which parser to use
The parser decides how broken HTML is repaired, and that changes what your selectors find. We parsed the same broken fragment with both:
html.parser <p>one<p>two</p></p>
lxml <html><body><p>one</p><p>two</p></body></html>Python's built-in html.parser nested the second paragraph inside the first, while lxml closed the first paragraph and added html and body. A browser closes the paragraph too, so lxml's tree is closer to what you see in developer tools. lxml is also faster. Use "lxml" when you can install it, and keep the same parser for the life of a scraper so that selectors keep matching.
Scrape politely, and through a proxy if you need one
- Read the site's
robots.txtand terms first. Is web scraping legal? covers what to check. - Wait between requests, as the scraper does, and set a timeout on every request.
- Send a user agent that says who you are.
If you need a proxy, for example to see prices as shoppers in another country see them, pass it on each request with proxies=. A proxy set as an environment variable silently overrides one set on the session, as our Python Requests guide shows.
Questions people ask
Is BeautifulSoup a web scraper?
Not by itself. It parses HTML that you have already downloaded and helps you find things in it. The downloading, waiting, retries and saving are up to your own code or another library, which is why it is almost always paired with Requests.
Should I use find or select?
Either. find and find_all read naturally in Python, while select and select_one let you reuse CSS selectors you have tested in the browser. Pick one style per project so the code stays consistent.
Why does get_text return text from child tags too?
Because get_text() collects all the text inside an element, including its children, as the Coffee 500 g example showed. Select the exact child you want, or pass a separator and strip=True to keep the pieces readable.
When BeautifulSoup is not enough
BeautifulSoup only sees the HTML the server sent. If the data is added by JavaScript after the page loads, look for the JSON request the page makes, or use a browser tool, as Playwright vs Selenium vs Puppeteer explains. For crawling many pages with scheduling and retries built in, a framework is the next step, and our Scrapy tutorial starts from the same site.
Try it yourself
Create an account, add funds from US$1 and order a proxy in the country you need.
Keep reading
25 Nov 2026 · Tutorials
Python HTTP clients compared: requests vs httpx vs aiohttp
A tested comparison of requests, httpx and aiohttp, including a benchmark where the run-to-run noise turned out to be larger than the gap people argue about.
25 Nov 2026 · Tutorials
How to find your proxy server address and port
Find the proxy your machine is already configured to use on Windows, macOS, Linux and in browsers, or find the host and port of a proxy you bought.