Thuta Learning
Python
ProjectsProgrammingBeginner

Web Scraper (Enhanced)

PythonLesson 6740 min

What you'll walk away with

  • Explain why terms of service, an official API and robots.txt come before any scraping
  • Use urllib.robotparser to check whether a URL is allowed and what crawl delay is requested
  • Extract data with BeautifulSoup's select() and select_one() and handle missing elements without crashing
  • Keep fetching separate from parsing and test the parser against a saved HTML string

Explain it simply

Explain it simply

Web scraping means a program does what a person would do with a browser and a spreadsheet: open a page, find the prices and copy them out. The program downloads the page's HTML and picks out the parts it needs.

But a program is far faster than a person. Someone browsing opens a few pages a minute; a loop can open thousands. So a good scraper behaves like a polite guest: it reads the host's rules, says who it is, takes its time, and does not trip over when the furniture has been moved.

Problem → Why → Solution

The problem: a scraper that is rude and fragile

The script below downloads 500 pages of a shop as fast as the loop can go. It never reads robots.txt, never checks the terms of service, and sends the default python-requests/... User-Agent, so the site owner has no idea who to contact. For a small server this looks like a flood, and it often ends with the IP being blocked.

The script is also fragile. When one product card has no price, card.find(...) returns None and .text raises AttributeError, killing the whole run. It never checks the status code either, so it tries to parse error pages as if they were products.

scraper_draft.py
import requests
from bs4 import BeautifulSoup

for page in range(1, 501):                       # 500 pages, no pause at all
    html = requests.get(f"https://shop.example.com/page-{page}").text
    soup = BeautifulSoup(html, "html.parser")
    for card in soup.find_all("div", class_="product"):
        name = card.find("h2").text
        price = float(card.find("span", class_="price").text[1:])  # None.text
        print(name, price)

Why does this happen?

The script mixes fetching, politeness and parsing in one loop. There is no step that checks permission, no step that spaces out requests, and it assumes the HTML always has the shape it expects. Websites change without warning, so that assumption breaks sooner or later.

Core concept: permission, politeness, defensive parsing

Think of a responsible scraper as two halves. Before fetching a page, you decide whether you may take it and how slowly. After fetching, you read HTML that may change, without crashing. The steps are these.

1. Ask permission first

Read the site's terms of service; they may forbid automated access. If there is an official API or data export, use it instead: it is more stable and the permission is clear. Then read /robots.txt, the Robots Exclusion Protocol. It is a request, not a lock, but responsible scrapers treat it as the site owner's rules. Python's urllib.robotparser checks it with can_fetch(user_agent, url).

2. Identify yourself

Send a descriptive User-Agent header such as BookPriceBot/1.0 (+mailto:you@example.com). If your bot causes trouble, the owner can contact you instead of simply blocking you.

3. Go slowly

Send one request at a time and wait between them. Honour a Crawl-delay line in robots.txt if there is one (it is not in the RFC standard, but it states the owner's wish); otherwise pick a delay of a second or more yourself. On 429 or 503, back off as the Retry-After header says. Use a timeout and cache pages you already have.

4. Parse defensively

select_one() returns None when nothing matches. Check for None before calling .get_text(), and skip and record a broken card instead of crashing. Turn relative links into absolute URLs with urljoin(), and store money as Decimal rather than float.

5. Keep fetching and parsing apart

If the parser takes an HTML string, you can save a page once and test against it as often as you like without touching the network. The main example works exactly this way.

BeautifulSoup callWhen nothing matches
select_one() / find()None
select() / find_all()an empty list []
tag["title"]raises KeyError
tag.get("title")None
Mental model: the polite guest
  1. Read the rules: ToS and robots.txt
  2. Say who you are: a User-Agent
  3. One page at a time, with a pause
  4. Parse HTML, checking for None
  5. Record what you had to skip

A 429 or a block is an answer from the site. Slow down or ask the owner; do not look for a way around it.

General pattern

python
robots = RobotFileParser()
robots.parse(robots_txt.splitlines())
if robots.can_fetch(USER_AGENT, url):
    soup = BeautifulSoup(html, "html.parser")
    for item in soup.select("css.selector"):
        part = item.select_one("child.selector")
        if part is None:
            continue                       # record it, do not crash
        value = part.get_text(strip=True)

Check permission first, select items with CSS selectors, and test each child element for None before reading its text.

A book price scraper, run offline

This example embeds a saved copy of robots.txt and one page of HTML as strings, so it needs no network. In a real program each string would come from one fetch. The third card has its price removed on purpose, to simulate the day the site changes its layout.

text
Where each part runs
--------------------
robots.txt + terms --> allowed? --no--> stop, ask the owner
                           |
                          yes
                           v
fetch page (User-Agent, timeout) --> wait crawl delay --> next page
          |
          v
HTML string --> parse cards --> rows + skipped list --> save / report
book_scraper.py
from decimal import Decimal
from urllib.parse import urljoin
from urllib.robotparser import RobotFileParser

from bs4 import BeautifulSoup

BASE = "https://books.example.com"
USER_AGENT = "BookPriceBot/1.0 (+mailto:you@example.com)"

# 1. Permission: read robots.txt (here a saved copy, normally fetched once)
ROBOTS_TXT = """
User-agent: *
Disallow: /cart
Disallow: /admin/
Crawl-delay: 2
"""
robots = RobotFileParser()
robots.parse(ROBOTS_TXT.splitlines())

page_url = BASE + "/catalogue/page-1.html"
print("allowed catalogue page:", robots.can_fetch(USER_AGENT, page_url))
print("allowed /cart:", robots.can_fetch(USER_AGENT, BASE + "/cart"))
print("crawl delay:", robots.crawl_delay(USER_AGENT), "seconds")

# 2. Parsing: the HTML a fetch would return (saved so the demo runs offline)
HTML = """
<html><body>
  <h1>New arrivals</h1>
  <article class="book">
    <h3><a href="python-crash-course.html"
           title="Python Crash Course">Python Cra...</a></h3>
    <p class="price">$39.99</p>
    <p class="stock">In stock</p>
  </article>
  <article class="book">
    <h3><a href="fluent-python.html" title="Fluent Python">Fluent Pyth...</a></h3>
    <p class="price">$54.50</p>
    <p class="stock">Out of stock</p>
  </article>
  <article class="book">
    <h3><a href="automate.html" title="Automate the Boring Stuff">Automate t...</a></h3>
    <p class="stock">In stock</p>
  </article>
</body></html>
"""

soup = BeautifulSoup(HTML, "html.parser")
books, skipped = [], []
for card in soup.select("article.book"):
    link = card.select_one("h3 a")
    price_tag = card.select_one("p.price")
    if link is None or price_tag is None:
        skipped.append(link["title"] if link else "unknown card")
        continue
    books.append({
        "title": link["title"],
        "price": Decimal(price_tag.get_text(strip=True).removeprefix("$")),
        "in_stock": card.select_one("p.stock").get_text(strip=True) == "In stock",
        "url": urljoin(page_url, link["href"]),
    })

for i, book in enumerate(books, 1):
    stock = "in stock" if book["in_stock"] else "sold out"
    print(f"{i}. {book['title']} | ${book['price']} | {stock}")
    print(f"   {book['url']}")
print(f"skipped {len(skipped)} card(s) with no price: {skipped}")

Code breakdown

  1. Load the rulesrobots.parse(ROBOTS_TXT.splitlines())

    parse() takes a list of lines. Against a live site you would call robots.set_url(BASE + "/robots.txt") and robots.read() once. A parser that has read no rules answers False for every URL.

  2. Ask before fetchingrobots.can_fetch(USER_AGENT, BASE + "/cart")

    Disallow rules match path prefixes, so blocking /cart also blocks /cart?item=3 and even /cartoons.

  3. One card at a timefor card in soup.select("article.book"):

    select() returns every element matching the CSS selector. Searching inside each card keeps one book's title from pairing with another book's price.

  4. Skip, do not crashif link is None or price_tag is None:

    A card without a price goes into the skipped list and the loop moves on. The final report shows how many were skipped, so a layout change is noticed immediately.

  5. The full title lives in an attribute"title": link["title"],

    The visible link text is cut short ("Python Cra..."), while the title attribute holds the full name. Always inspect the HTML source before choosing what to extract.

  6. Exact money, absolute links"url": urljoin(page_url, link["href"]),

    href="fluent-python.html" is relative, so urljoin() combines it with the page URL. The price, with "$" removed, is stored as Decimal, so there is no rounding error.

You should see
allowed catalogue page: True
allowed /cart: False
crawl delay: 2 seconds
1. Python Crash Course | $39.99 | in stock
   https://books.example.com/catalogue/python-crash-course.html
2. Fluent Python | $54.50 | sold out
   https://books.example.com/catalogue/fluent-python.html
skipped 1 card(s) with no price: ['Automate the Boring Stuff']

Content that requests cannot see

requests downloads only the first HTML the server sends; it does not run JavaScript. If a page fills in its products with JavaScript after loading, you will see them in the browser, yet soup.select() returns an empty list.

To check, open the browser's "View page source", not the DevTools Elements panel, which shows the DOM after scripts have run. If the data is not in the source, the page usually loads it from a JSON endpoint. That endpoint falls under the same terms and robots rules, and asking for an official API is still the better route. Browser automation tools exist, but they are heavier and outside this lesson.

In real projects

In real projects

Price-monitoring tools, job-listing aggregators, academic research datasets and web archives all rely on scraping. Long-running projects store the raw HTML on disk, so a parser bug can be fixed and the pages re-parsed without downloading the site again. They schedule runs at quiet hours and watch the count of skipped cards; when the skip rate suddenly jumps, an alert says the site has changed its layout.

There is a legal and ethical side too. Reading a page is different from republishing its content, which may be copyrighted. Collecting personal data such as names or emails can bring privacy laws like the EU's GDPR into play. In company projects, asking the legal team before starting a scraper is normal practice.

Common mistakes

Common mistakes

Hammering the site

A loop with no delay, or many threads downloading in parallel, can slow down or take down a small server and hurt its other users. Keep one request at a time with a delay in between.

Disguising the bot as a browser to dodge a block

Copying Chrome's User-Agent string to keep going after a block deceives the owner. A block is an answer that means stop; contact the owner or look for an API.

Chaining .find().text without a check

When the element is missing, find() returns None and None.text raises AttributeError: 'NoneType' object has no attribute 'text', stopping the whole run. Store the result in a variable and test it for None.

Forgetting status codes and JavaScript

Parsing a 404 page or a login page yields zero products and no error at all. Check resp.status_code, and when results come back empty, check whether JavaScript fills in the content.

Mini challenge

Build a PoliteFetcher

Write a PoliteFetcher that checks every URL against robots.txt, sends a User-Agent, waits at least delay seconds between requests, and on a 429 backs off for Retry-After seconds and tries once more. The session, clock and sleep function are injected, so the test runs instantly on virtual time.

  • Skip a URL that robots.txt disallows without sending a request, and return None
  • Every request carries the User-Agent header and a timeout
  • If fewer than delay seconds have passed since the last request, sleep only for the remainder
  • On a 429, sleep for Retry-After seconds and retry once
polite_fetcher.py
from urllib.robotparser import RobotFileParser


class PoliteFetcher:
    def __init__(self, session, robots, user_agent, delay, clock, sleep):
        # TODO: keep every argument; build the headers dict;
        #       remember when the last request started (None at first)
        ...

    def _wait_turn(self):
        # TODO: sleep for whatever is left of self.delay, then record the time
        ...

    def fetch(self, url):
        # TODO: return None (and say why) when robots.txt disallows the url
        # TODO: up to two attempts: wait your turn, send the GET
        # TODO: on 429 read Retry-After, sleep that long, then try again
        ...


# TODO: fake session + virtual clock: now = [0.0]; sleep adds to now[0]

Expected: page-1 is fetched at t=0.0, the fetcher sleeps 1.5s before page-2, page-2 answers 429 so it backs off 5s and gets 200 on the second try, and /cart is skipped by robots.txt without any request.

Show hint

Record last_request with self.clock() when a request starts. gap = self.clock() - self.last_request, and if gap < self.delay call self.sleep(self.delay - gap). Retry-After can also be an HTTP date; this challenge only needs the seconds form.

Show solution
polite_fetcher.py
from urllib.robotparser import RobotFileParser


class PoliteFetcher:
    def __init__(self, session, robots, user_agent, delay, clock, sleep):
        self.session = session
        self.robots = robots
        self.headers = {"User-Agent": user_agent}
        self.user_agent = user_agent
        self.delay = delay
        self.clock = clock
        self.sleep = sleep
        self.last_request = None

    def _wait_turn(self):
        if self.last_request is not None:
            gap = self.clock() - self.last_request
            if gap < self.delay:
                self.sleep(self.delay - gap)
        self.last_request = self.clock()

    def fetch(self, url):
        if not self.robots.can_fetch(self.user_agent, url):
            print(f"skip (robots.txt): {url}")
            return None
        for attempt in (1, 2):
            self._wait_turn()
            resp = self.session.get(url, headers=self.headers, timeout=10)
            if resp.status_code != 429:
                return resp
            wait = int(resp.headers.get("Retry-After", "30"))
            print(f"429 on attempt {attempt}, backing off {wait}s")
            self.sleep(wait)
        return None


# ---- fakes: virtual time, a session that answers from a script ----
now = [0.0]


def fake_sleep(seconds):
    print(f"  (sleep {seconds:.1f}s)")
    now[0] += seconds


class FakeResponse:
    def __init__(self, status_code, text="", headers=None):
        self.status_code = status_code
        self.text = text
        self.headers = headers or {}


class FakeSession:
    def __init__(self, script):
        self.script = script

    def get(self, url, headers=None, timeout=None):
        print(f"GET {url} as {headers['User-Agent'].split()[0]} at t={now[0]:.1f}")
        now[0] += 0.5  # pretend the download took half a second
        return self.script[url].pop(0)


robots = RobotFileParser()
robots.parse(["User-agent: *", "Disallow: /cart"])
site = "https://books.example.com"
session = FakeSession({
    site + "/page-1": [FakeResponse(200, "<html>1</html>")],
    site + "/page-2": [FakeResponse(429, headers={"Retry-After": "5"}),
                       FakeResponse(200, "<html>2</html>")],
})
fetcher = PoliteFetcher(session, robots, "BookPriceBot/1.0 (+mailto:you@example.com)",
                        delay=2.0, clock=lambda: now[0], sleep=fake_sleep)

for path in ["/page-1", "/page-2", "/cart"]:
    resp = fetcher.fetch(site + path)
    if resp is not None:
        print("  ->", resp.status_code, resp.text)

Quick quiz 1 / 3

robots.txt contains only "User-agent: *" and "Disallow: /cart". What does robots.can_fetch(UA, "https://books.example.com/cartoons") return?

Quick quiz 2 / 3

What happens when you call card.select_one("p.price").get_text() on a card that has no price element?

Quick quiz 3 / 3

Your scraper receives 429 Too Many Requests with Retry-After: 120. What is the right response?

What to remember

  • Check the terms of service, any official API and robots.txt before scraping
  • Send a contactable User-Agent, one request at a time with a delay, and back off on 429
  • Test select_one() results for None, and skip and record broken cards
  • Keep parsing separate from fetching so the parser can be tested on an HTML string

Requests — User Guide — Requests

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Web Scraper (Enhanced) | Thuta Learning