Web Scraping & HTML Parsing
Module 4
Extracting structured data from web pages using Python, BeautifulSoup, and XPath techniques
© 2026 WayUp
Web Scraping = extracting data from regular web pages
HTML = Hyper Text Markup Language
html filesHTML is a markup language, close to XML, but with less constraintsHTML elements have opening and closing tags:
<article class="product_pod">
<h3><a href="..." title="A Light in the Attic">A Light in...</a></h3>
<p class="price_color">£51.77</p>
<p class="star-rating Three">
<i class="icon-star"></i>
</p>
</article>
We can target elements using CSS selectors or XPath expressions.
What you see is not always what you fetch!
import requests
from bs4 import BeautifulSoup
url = "http://books.toscrape.com"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html.parser")
# Find all book elements
books = soup.select("article.product_pod")
for book in books[:5]:
title = book.select_one("h3 a")["title"]
price = book.select_one(".price_color").text
print(f"{title}: {price}")
from lxml import html
import requests
response = requests.get("http://books.toscrape.com")
tree = html.fromstring(response.content)
# XPath to select all book titles and prices
titles = tree.xpath("//article[@class='product_pod']//h3/a/@title")
prices = tree.xpath("//p[@class='price_color']/text()")
for title, price in zip(titles[:5], prices[:5]):
print(f"{title}: {price}")
Goal: Extract HDI data as fast as possible
# Using Selenium for JavaScript-heavy sites
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument('--headless')
driver = webdriver.Chrome(options=options)
driver.get("https://example.com")
# Now you can access JavaScript-rendered content
Short answer: when you cannot do otherwise
Longer answer: beware of the automation cost - verify that it is worth it!
import requests
from bs4 import BeautifulSoup
from Orange.data import Table, Domain, StringVariable, ContinuousVariable
# Scrape book data
response = requests.get("http://books.toscrape.com")
soup = BeautifulSoup(response.content, "html.parser")
# Extract data
data = []
for book in soup.select("article.product_pod"):
title = book.select_one("h3 a")["title"]
price = float(book.select_one(".price_color").text[1:])
data.append([title, price])
# Create Orange table
domain = Domain([StringVariable("title")], [ContinuousVariable("price")])
out_data = Table.from_list(domain, data)
Scrape books.toscrape.com and analyze the data in Orange:
Web Scraping & HTML Parsing
Next: Practical Work Sessions
© 2026 WayUp - way-up.io