Web scraping
How do I parse HTML with Beautiful Soup?
Pass the HTML string and a parser name to BeautifulSoup, then query the resulting tree with CSS selectors or find methods and read text or attributes off each match.
The short version
Install beautifulsoup4, create a soup with BeautifulSoup(html_text, "html.parser"), and search it. select() takes CSS selectors and returns a list, select_one() returns the first match or None, and every match exposes .get_text() and attribute access. That covers most extraction jobs; the rest of this page is about doing it without fragile code.
A complete small example
The script below fetches a listing page, walks each product card and builds plain dictionaries. It uses Requests for the download, but the parsing part is the same whatever fetched the HTML.
import requests, bs4
resp = requests.get("https://shop.example.net/catalog?page=1", timeout=20)
resp.raise_for_status()
soup = bs4.BeautifulSoup(resp.text, "html.parser")
items = []
for card in soup.select("li.product-tile"):
title_tag = card.select_one("h3 a")
cost_tag = card.select_one("[data-role=price]")
items.append({
"title": title_tag.get_text(strip=True) if title_tag else None,
"url": title_tag["href"] if title_tag else None,
"price": cost_tag.get_text(strip=True) if cost_tag else None,
})
print(len(items), items[:2])
Choosing a parser
Beautiful Soup does not parse by itself; it wraps a parser. The built in html.parser needs nothing extra. lxml is a separate install and is usually the fastest. html5lib repairs broken markup the way a browser does, at a much slower pace. Pick one and keep it, because the three can build slightly different trees from the same messy HTML, and a selector tested on one may miss on another.
The search methods you will use most
select("css")andselect_one("css"): the most readable option for anyone who knows CSS selectors.find(name, attrs)andfind_all(...): useful when you match on a function or a regular expression instead of a fixed selector.tag["href"]raisesKeyErrorif the attribute is missing, whiletag.get("href")returnsNone.get_text(" ", strip=True)joins nested text with a space and trims whitespace, which avoids words glued together across tags.
Matching by class name has its own quirks (multiple classes, partial names); the page on finding elements by class covers them.
Mistakes that cost the most time
Assuming a match exists. Calling .get_text() on the result of select_one crashes with AttributeError: 'NoneType' the first time a card lacks that field. Guard each optional field, as in the example.
Parsing the wrong document. If the data is drawn by JavaScript, the HTML your client downloaded simply does not contain it. Print a slice of resp.text and search it for a value you can see in the browser before writing selectors. When the value is missing, the content is dynamic and you need either the site's JSON endpoint or a browser; static or dynamic page explains how to tell.
Parsing a block page. A soup built from a CAPTCHA or challenge page parses fine and returns empty lists, which looks like a selector bug. Check the status code and look for markers such as a g-recaptcha div or a Turnstile widget before you parse. If a check page is in the way, the Python scraping guide shows where a solving step fits in the flow.
Relative links and encodings
Attribute values come back exactly as written in the markup, so href is often relative. Join it with the page address using urllib.parse.urljoin(resp.url, href). For text, let Requests guess the encoding from headers, and if you see garbled characters, pass resp.content (bytes) to BeautifulSoup instead so it can read the charset declared in the page.
Cleaning values as you extract
Text from a page is rarely ready to store. Prices arrive as "$1,299.00" or "1.299,00 EUR", dates in local formats, and names with trailing badges such as "New". Keep extraction and cleaning separate: the parsing function returns raw strings, and a second function converts them into numbers, dates and enums. When a value fails to convert, log the raw string and the page URL. That log tells you quickly whether the site changed a format or your selector started picking up the wrong element.
When Beautiful Soup is not enough
It parses one document at a time and has no crawler, scheduler or retry logic. For a few pages a day that is ideal. For thousands of pages with link following, the comparison of Scrapy and Beautiful Soup helps you decide when to move to a framework.
Common questions
Do I need lxml installed to use Beautiful Soup?
No. The built in html.parser works out of the box; lxml is optional and mainly adds speed.
Why does select_one return None when I can see the element?
The element is probably added by JavaScript after load, so it is not in the HTML your client downloaded.
How do I read a data attribute?
Use tag.get("data-id") or tag["data-id"]; data attributes are ordinary attributes to the parser.
Can Beautiful Soup run JavaScript?
No. It only parses markup. Render the page in a browser first if the content depends on scripts.
Is Beautiful Soup fast enough for large jobs?
With the lxml parser it handles typical pages quickly; downloading is usually the slower part of a scraper.
Keep reading
- Beautiful SoupThe forgiving Python library for parsing HTML and XML into a tree you can search by tag, attribute or CSS selector.
- HTML parsingHTML parsing turns markup into a tree your code can query, and tolerant parsers rebuild broken pages the same way browsers do.
- Can XPath be used in Beautiful Soup?Beautiful Soup has no XPath engine; use its CSS select method, or parse the same HTML with lxml when you need XPath.
- Web scraping with Python: a working guideFrom the first request to a polite, restartable scraper in Python: sessions, parsing, pagination, retries and where CAPTCHAs fit in.