Parsing HTML in Python
Turning markup into a searchable tree with BeautifulSoup.
from bs4 import BeautifulSoup
html = """
<html>
<body>
<h1 id="title">Typing for Coders</h1>
<p class="lead">Practice real code.</p>
<a href="/start">Begin</a>
</body>
</html>
"""
soup = BeautifulSoup(html, "html.parser")
heading = soup.find("h1").get_text()
lead = soup.find("p", class_="lead").text
link = soup.find("a")["href"]
title_id = soup.find(id="title").get("id")
How it works
BeautifulSoup(html, 'html.parser')builds the tree.findlocates the first matching tag.get_textand['href']read content and attributes.
Keywords and builtins used here
id
The run, in numbers
- Lines
- 17
- Characters to type
- 375
- Tokens
- 103
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 59 seconds.
Step 1 of 3 in BeautifulSoup, step 6 of 9 in Web scraping.