Parsing HTML with BeautifulSoup
Install
Section titled “Install”Common package name: beautifulsoup4
Parse HTML
Section titled “Parse HTML”from bs4 import BeautifulSoup
html = """
<html><body>
<h1 class='title'>Hello</h1>
<a href='https://example.com'>Link</a>
</body></html>
"""
soup = BeautifulSoup(html, "html.parser")
print(soup.h1.get_text(strip=True))
print(soup.a["href"])Find elements
Section titled “Find elements”from bs4 import BeautifulSoup
soup = BeautifulSoup("<p class='x'>A</p><p class='y'>B</p>", "html.parser")
print(soup.find("p", class_="y").text)
print([p.text for p in soup.find_all("p")])Use CSS selectors
Section titled “Use CSS selectors”from bs4 import BeautifulSoup
soup = BeautifulSoup("<div><span class='price'>$10</span></div>", "html.parser")
print(soup.select_one("span.price").text)🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – List Files with os.listdir
Section titled “Exercise 1 – List Files with os.listdir”Exercise 2 – Join Paths with os.path.join
Section titled “Exercise 2 – Join Paths with os.path.join”Exercise 3 – Write and Read a File
Section titled “Exercise 3 – Write and Read a File”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading