Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Web scraping with Python

Practical, exam-focused notes on web scraping with Python: definitions, pipeline, safe/ethical rules, key libraries (requests, BeautifulSoup, Selenium), example programs, and common exam questions.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Web scraping is the automated extraction of information from web pages. Engineers use scraping to collect training data, monitor prices, gather documents for search engines, and build datasets when a public API is not available.

Key ideas

  • HTML: HyperText Markup Language, tree-structured documents. A DOM (Document Object Model) is the tree representation of HTML: draw a small tree for a page with html -> body -> div -> h1, p, a and label nodes.

  • Parser: software that converts HTML text to a DOM. Examples: the Python built-in parser 'html.parser', the faster C-based 'lxml' parser.

  • Selector: a way to find nodes in the DOM. Two common types:

    • CSS selectors (use class, id, tag: .product a, #main p).
    • XPath (path expressions like //div[@class='product']/a).
  • Session / Cookies: a session stores cookies and headers across requests. Use a session if the site requires login or tracks state.

  • User‑Agent and headers: servers may block unknown clients. A User‑Agent header identifies the client. Example header key: User-Agent.

  • robots.txt: a file at /robots.txt that declares what automated agents are allowed or disallowed. It is a convention (not an enforcement mechanism) but a widely respected one. Use urllib.robotparser to check rules programmatically.

  • Politeness (rate limiting): do not overload servers. Implement delays (e.g., time.sleep) and exponential backoff on errors.

  • Ethics and legality: scraping public HTML can still be legally restricted by terms of service; check site terms and local law. Always prefer using a provided API.

  • Dynamic (JavaScript) pages: some pages render data client-side using JavaScript. To scrape these you need a renderer (headless browser like Chrome via Selenium, or tools like Playwright, or the site's API endpoints used by JS).

  • Pipeline steps (exact algorithm universities expect):

    1. Fetch page: send HTTP GET (include headers, handle status codes). Assumption: network available and URL valid.
    2. Parse HTML into a DOM with a parser (specify parser name).
    3. Select nodes using CSS selectors or XPath.
    4. Extract data from node attributes or text (use .get('href'), .text).
    5. Clean data (strip whitespace, convert types such as price -> float).
    6. Store results (CSV, JSON, database).

    Draw a flowchart boxes: Fetch -> Parse -> Select/Extract -> Clean -> Store. Label any loops for pagination.

  • Pagination and crawling: if scraping multiple pages, either follow pagination links or generate URLs. Avoid infinite loops by detecting repeated URLs or maximum depth.

  • Error handling: check response.status_code, handle 4xx/5xx, use try/except to handle network and parsing errors.

Formulas

(For a programming topic we list syntax to remember.)

  • import requests — import the requests HTTP library.
  • response = requests.get(url, headers=headers, timeout=10) — fetch a page; timeout in seconds.
  • s = requests.Session(); resp = s.get(url, headers=headers, timeout=10) — use a session to persist cookies and headers across requests.
  • response.raise_for_status() — raise an exception for 4xx and 5xx responses (status >= 400).
  • response.status_code — integer HTTP status code.
  • from bs4 import BeautifulSoup
  • soup = BeautifulSoup(response.text, 'html.parser') — parse HTML to a DOM.
  • element = soup.find('h1') — find first matching tag.
  • elements = soup.find_all('a', class_='link') — list of tags matching criteria.
  • element.get('href') — get attribute value.
  • element.text.strip() — get text content, trimmed.
  • soup.select('div.product > a.title') — CSS selector extraction.
  • import urllib.robotparser / rp = urllib.robotparser.RobotFileParser() / rp.set_url('https://example.com/robots.txt') / rp.read() / rp.can_fetch('*', url) — check robots.txt.
  • from selenium import webdriver — create a browser for JS-rendered pages; then driver.get(url) and html = driver.page_source.
  • time.sleep(seconds) — polite delay between requests.
  • import csv — CSV module; then with open('data.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f); writer.writerow(...) — storing data to CSV.

Worked examples

Example 1 — parse a known HTML string (deterministic, runs anywhere).

Python program:

# example1_parse_local.py
from bs4 import BeautifulSoup

html = '''
<html>
  <body>
    <ul class="products">
      <li class="product"><a href="/p1">Product A</a> <span class="price">₹199.00</span></li>
      <li class="product"><a href="/p2">Product B</a> <span class="price">₹299.50</span></li>
    </ul>
  </body>
</html>
'''

soup = BeautifulSoup(html, 'html.parser')
items = []
for li in soup.select('ul.products li.product'):
    name = li.find('a').text.strip()
    href = li.find('a').get('href')
    price_text = li.find('span', class_='price').text.strip()
    # simple cleaning: remove currency symbol and convert to float
    price = float(price_text.replace('₹', '').replace(',', ''))
    items.append((name, href, price))

for it in items:
    print(it)

Sample input: none (HTML string embedded in code).

Exact output when run:

('Product A', '/p1', 199.0)
('Product B', '/p2', 299.5)

Example 2 — fetch a stable public page (example.com) and extract title and first paragraph.

Python program:

# example2_fetch_exampledotcom.py
import requests
from bs4 import BeautifulSoup

url = 'http://example.com'
headers = {'User-Agent': 'Mozilla/5.0 (compatible; ExampleBot/1.0)'}
resp = requests.get(url, headers=headers, timeout=10)
resp.raise_for_status()

soup = BeautifulSoup(resp.text, 'html.parser')
h1 = soup.find('h1')
p = soup.find('p')

print('H1:', h1.text.strip())
print('P:', p.text.strip())

Sample input: none (script fetches the page).

Exact output (text from example.com as of standard stable content):

H1: Example Domain
P: This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission.

Notes: network must be available. If the HTML on example.com changes, the output may differ.

Common mistakes

  • Parsing fragile selectors (for example, using absolute XPath like /html/body/div[2]/ul/li[1]); prefer class-based selectors or fallback logic.
  • Not handling character encoding; use response.encoding or response.text and check response.apparent_encoding if needed.
  • Not catching requests exceptions (ConnectionError, Timeout) and not using raise_for_status().
  • Ignoring rate limits and hammering the server (no time.sleep, no backoff), which leads to IP bans.
  • Assuming all pages have the same structure (no checks for None before .text or .get('href')).

For your exam

Quick check

  1. What file tells automated agents which paths are disallowed on a website?
  2. Name two ways to select nodes in a DOM for extraction.
  3. Why use a session object in requests?

Answers: robots.txt; CSS selectors and XPath; to persist cookies and headers across multiple requests and maintain state.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?