AI & Data

Web Scraping & HTML Parsing

Module 4

Extracting structured data from web pages using Python, BeautifulSoup, and XPath techniques

<div> <p> <a> <td>

What is Web Scraping?

Web Scraping = extracting data from regular web pages

Web Scraping Pipeline
Step 1: Fetch Target URL HTTP Request Response 200 OK? Error Yes Step 2: Parse Parse HTML BeautifulSoup Locate CSS/XPath Step 3: Extract Extract Data title, price... Create DataFrame pd.DataFrame()

Understanding HTML

HTML = Hyper Text Markup Language

Key difference: HTML is designed for display, while XML is designed for data transport.

HTML Structure Example

HTML 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.

DOM vs HTML

What you see is not always what you fetch!

Browser Rendering Pipeline
Server Raw HTML May have errors Browser (What Users See) Parse & Fix Error tolerance Execute JS Dynamic content Rendered DOM What you see! Python Scraper (What Code Gets) requests.get() Raw HTML only! No JavaScript No dynamic content VS
Important: Python gets the raw HTML, not the JavaScript-rendered content!

books.toscrape.com - A Safe Scraping Sandbox

Best Practice: Always use practice sites like toscrape.com before scraping real websites.

Scraping with BeautifulSoup

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}")

Same Task with lxml and XPath

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}")

Exercise: Manual Data Extract

Goal: Extract HDI data as fast as possible

  1. Navigate to Wikipedia HDI page
  2. Think about the best way to extract the HDI table
  3. Produce a CSV from it as fast as you can
Hint: Sometimes manual copy-paste is faster than writing code!

Limits of Direct HTML Fetching

# 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

When to Use Scraping?

Short answer: when you cannot do otherwise

Longer answer: beware of the automation cost - verify that it is worth it!

Remember: APIs are always preferable to scraping when available.

Integrating Scraped Data with Orange

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)

Exercise: Scrape and Analyze Book Data

Scrape books.toscrape.com and analyze the data in Orange:

Multi-Page Scraping Pipeline
📚 toscrape.com Page 1 Page 2 ... Page N For Each Page Fetch HTML Find all books Extract: title, price, rating Combine Merge all 60 books Orange Data Table Chart Price distribution

Questions?

Web Scraping & HTML Parsing

Next: Practical Work Sessions

Slide Overview