Intermediate   Chapter 181 · 35 min read · Module 14: Advanced Application Development

Web Scraping Fundamentals

Learning objectives
  • After this chapter you can explain what web scraping is and when an API is a better choice.
  • You can describe the structure of an HTML page as tags, attributes and text.
  • You can extract text and links from HTML using html.parser from the standard library.
  • You can build and resolve URLs with urllib.parse.
  • You can follow basic rules for polite and legal scraping such as robots.txt and rate limits.

Web scraping means using a program to collect information from web pages. Instead of copying prices, headlines or tables by hand, you write code that downloads a page, finds the parts you care about and saves them in a clean form such as a list or a CSV file.

A web page is just text written in HTML. Once you understand how that text is organised, reading it with Python is a matter of finding the right tags. In this chapter we practise on HTML stored in a string, so every example runs offline, and we explain how the same ideas apply to real pages.

Scraping also comes with responsibility. You need to respect the rules of each website, avoid sending too many requests and prefer an official API whenever one exists. We finish the chapter with these good habits.

What is web scraping?

Scraping has three steps. First you fetch the page, usually with an HTTP request. Second you parse the HTML so that your program can see its structure. Third you extract the values you want and store them. Most scraping bugs come from the second and third steps, because pages are written for people, not for programs.

Web scraping: the automatic collection of data from web pages by a program

Before you scrape, check whether the site offers an API. An API returns data in a clean format such as JSON and is meant for programs. Scraping is the fallback when no API exists, and it is more fragile because a small change in the page layout can break your code.

The shape of an HTML page

HTML is made of elements. An element usually has an opening tag like <li>, some content and a closing tag like </li>. A tag can carry attributes such as class="book" or href="/b/1". Elements can sit inside other elements, which forms a tree. The <ul> list contains <li> items, and each item may contain a link <a> and a <span>.

PartExampleMeaning
Tag<a>Kind of element, here a link
Attributehref="/b/1"Extra information in the opening tag
TextPython BasicsThe visible content
Classclass="book"Label often used to find elements

Parsing with the standard library

Python ships with html.parser.HTMLParser. You make a subclass and write methods that are called when the parser meets a start tag, an end tag or some text. This needs no installation. Popular third party tools such as Beautiful Soup are easier to use, but the idea is the same: walk through the tags and collect what you need.

Example 1: collect link addresses and texts
html = """<html><body>
<h1>Books</h1>
<ul>
<li class=\"book\"><a href=\"/b/1\">Python Basics</a> <span>$10</span></li>
<li class=\"book\"><a href=\"/b/2\">Data Tricks</a> <span>$15</span></li>
</ul>
</body></html>"""
from html.parser import HTMLParser

class LinkParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.links = []
        self._href = None

    def handle_starttag(self, tag, attrs):
        if tag == "a":
            self._href = dict(attrs).get("href")

    def handle_data(self, data):
        if self._href is not None:
            self.links.append((self._href, data))
            self._href = None

parser = LinkParser()
parser.feed(html)
print(parser.links)
[('/b/1', 'Python Basics'), ('/b/2', 'Data Tricks')]

In the example, handle_starttag receives the tag name and a list of attribute pairs. Converting that list with dict(attrs) makes it easy to look up href. The next piece of text after the link tag is the visible link text, which handle_data stores together with the address.

Extracting prices

Real data is rarely clean. A price like $15 is text with a currency sign. To use it you strip the sign and convert the rest to a number. Regular expressions are also common for such cleanup, but simple string methods are often enough and easier to read.

Example 2: prices from span tags
html = """<html><body>
<h1>Books</h1>
<ul>
<li class=\"book\"><a href=\"/b/1\">Python Basics</a> <span>$10</span></li>
<li class=\"book\"><a href=\"/b/2\">Data Tricks</a> <span>$15</span></li>
</ul>
</body></html>"""
from html.parser import HTMLParser

class PriceParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.in_span = False
        self.prices = []

    def handle_starttag(self, tag, attrs):
        self.in_span = tag == "span"

    def handle_endtag(self, tag):
        if tag == "span":
            self.in_span = False

    def handle_data(self, data):
        if self.in_span:
            self.prices.append(int(data.strip("$")))

p = PriceParser()
p.feed(html)
print(p.prices, sum(p.prices))
[10, 15] 25

Working with URLs

Links on a page are often relative, like /b/1. To fetch them you must join them with the address of the page. The function urllib.parse.urljoin does this. urlparse splits an address into parts such as the host and the path, and urlencode builds a safe query string from a dictionary.

Example 3: join and split URLs
from urllib.parse import urljoin, urlparse, urlencode

base = "https://example.com/shop/"
print(urljoin(base, "/b/1"))
print(urljoin(base, "item.html"))
parts = urlparse("https://example.com/search?q=python&page=2")
print(parts.netloc, parts.path, parts.query)
print(urlencode({"q": "python tips", "page": 2}))
https://example.com/b/1 https://example.com/shop/item.html example.com /search q=python&page=2 q=python+tips&page=2

Fetching a page

To download a page you can use urllib.request.urlopen or the popular requests library, which you install with pip. Always set a timeout so your program does not wait forever, and check the status code before you parse. Because this needs the network, the next example is shown but not run here.

Example 4: fetch a page with requests (needs network)
import requests

response = requests.get("https://example.com", timeout=10)
print(response.status_code)
print(response.text[:15])
200 <!doctype html>

Scraping politely and legally

  • Read the site's terms of service and its robots.txt file, which lists the paths that automated programs should avoid.
  • Add a pause between requests, for example with time.sleep(1), so you do not overload the server.
  • Identify your program with a clear User-Agent header.
  • Do not collect private or personal data, and do not bypass logins or protections.
  • Cache pages you have already downloaded instead of fetching them again.
  • Prefer an official API when there is one.
Some pages build their content with JavaScript after loading. A simple download will not contain that content. In such cases look for a hidden JSON data source in the browser's network tab or use a browser automation tool.

Python syntax

Syntax
from html.parser import HTMLParser
class P(HTMLParser):
    def handle_starttag(self, tag, attrs): ...
    def handle_data(self, data): ...
Syntax
from urllib.parse import urljoin
urljoin(base, relative)
Syntax
import requests
r = requests.get(url, timeout=10)
html = r.text

Real-world applications

  • Collecting product prices for comparison.
  • Gathering news headlines or job listings.
  • Building datasets for research or machine learning.
  • Monitoring a page for changes.
  • Archiving public documents.

Common mistakes

Mistake: Scraping a site without checking robots.txt or the terms of service.
Fix: Read both first and follow the rules. Use an API if available.
Mistake: Sending requests in a fast loop with no pause.
Fix: Use time.sleep between requests and limit how many pages you fetch.
Mistake: Forgetting a timeout on requests.get, so the program may hang.
Fix: Always pass timeout=10 or a similar value.
Mistake: Assuming every element exists, which fails when the layout changes.
Fix: Check for missing values and write code that handles None.
Mistake: Trying to build paths by joining strings with +.
Fix: Use urljoin, which handles slashes and relative paths correctly.

Important tips

  • Develop your parser on a saved copy of the page first.
  • Inspect the page with your browser's developer tools to find tags and classes.
  • Save raw HTML so you can re-parse without downloading again.
  • Write the extracted data to CSV or JSON.
  • Handle errors and retry carefully.

Key points summary

  • Scraping = fetch, parse, extract.
  • HTML is a tree of elements with attributes and text.
  • html.parser is in the standard library.
  • urljoin turns relative links into full addresses.
  • Be polite: robots.txt, delays and timeouts.

Exam and interview points

  • Name the three steps: fetch, parse, extract.
  • Know that attrs in handle_starttag is a list of (name, value) pairs.
  • urljoin resolves relative links.
  • robots.txt tells bots which paths to avoid.
  • An API is preferred over scraping when available.

Quick revision

  • Fetch, parse, extract.
  • Elements have tags, attributes and text.
  • HTMLParser uses handle_starttag and handle_data.
  • dict(attrs).get('href') reads a link.
  • urljoin fixes relative links.
  • Sleep between requests.

Frequently asked questions

Is web scraping legal?

It depends on the site, the data and your country. Public facts are often allowed, but terms of service, copyright and privacy laws can limit you. When unsure, ask for permission or use an API.

Why not use regular expressions to parse HTML?

HTML is nested and messy, and regular expressions break easily on it. A parser understands the structure. Regular expressions are fine for small cleanup such as cleaning a price.

What is the difference between html.parser and Beautiful Soup?

html.parser is built in and works with callbacks. Beautiful Soup is a separate package that gives you a simple tree you can search with methods such as find_all.

Why does my scraper see an empty page?

The content may be created by JavaScript after the page loads. Look for a JSON data request in the network tab or use a browser automation tool.

How do I avoid being blocked?

Scrape slowly, use a clear User-Agent, respect robots.txt and cache results. Heavy or hidden scraping often leads to blocks.

Practise this chapter

19 practice questions Take the chapter quiz

Related chapters