Rana Maninder Singh
Lesson 4 of 11Python Advanced

Web Scraping — requests, BeautifulSoup & Ethics

Lesson opener

In one line: Fetch web pages with requests.

Why it matters: This shows up at work when you need to fetch web pages with requests.

Before this lesson: Pandas basics / Files & exceptions

Before you start

ResourceLink
PreviousOOP in Python
NextPython & SQL
PrerequisitesPandas basics, Files & exceptions
Time~50 minutes
What you needpip install requests beautifulsoup4 lxml pandas

What you will learn

  • Fetch web pages with requests
  • Parse HTML with BeautifulSoup
  • Extract tables and text into a pandas DataFrame
  • Ethics: robots.txt, rate limits, terms of service, and when not to scrape

Section 1 — When scraping makes sense

Plain English:

Your manager asks for competitor prices, government tariff PDFs, or job listings — and there is no API or database. Scraping means programmatically reading public HTML and pulling structured data out.

Use scrapingUse something else
Public price lists, no APIOfficial API or CSV download
One-off research projectPaid data vendor
Internal dashboard HTMLread_sql from your DB

Legal and ethical rule: If a site forbids scraping in its Terms of Service, or blocks you in robots.txt, respect that. This lesson uses public example pages and teaches patterns — not bypassing paywalls or login walls.


Section 2 — Fetch a page with requests

import requests

url = "https://example.com"
response = requests.get(url, timeout=10)
response.raise_for_status()  # error on 404/500

print(response.status_code)  # 200
print(response.text[:500])   # first 500 chars of HTML

Breaking it down:

Headers (good practice):

headers = {"User-Agent": "LearningBot/1.0 (educational; contact@example.com)"}
response = requests.get(url, headers=headers, timeout=10)

Section 3 — Parse with BeautifulSoup

from bs4 import BeautifulSoup

soup = BeautifulSoup(response.text, "lxml")

# Page title
print(soup.title.string)

# All links
for a in soup.find_all("a", href=True):
    print(a.get_text(strip=True), "→", a["href"])
MethodPurpose
soup.find("tag", class_="x")First matching element
soup.find_all("tr")All table rows
.get_text(strip=True)Text content, whitespace trimmed
element["href"]Attribute value

Section 4 — Scrape a table into DataFrame

Many public pages expose data in <table> tags. Pandas can read HTML tables directly:

import pandas as pd

url = "https://en.wikipedia.org/wiki/List_of_states_and_union_territories_of_India_by_population"
tables = pd.read_html(url)
print(len(tables), "tables found")
df = tables[0]
df.head()

When read_html fails (messy markup), parse manually:

import requests
from bs4 import BeautifulSoup
import pandas as pd

url = "https://example.com/sample-table-page"
r = requests.get(url, timeout=10)
soup = BeautifulSoup(r.text, "lxml")

rows = []
table = soup.find("table", {"id": "data"})
for tr in table.find_all("tr")[1:]:  # skip header row
    cells = [td.get_text(strip=True) for td in tr.find_all("td")]
    if cells:
        rows.append(cells)

df = pd.DataFrame(rows, columns=["name", "value", "date"])
df.head()

Section 5 — Store and clean results

df["value"] = pd.to_numeric(df["value"].str.replace(",", ""), errors="coerce")
df["date"] = pd.to_datetime(df["date"], errors="coerce")
df = df.dropna(subset=["value"])

df.to_csv("outputs/scraped_data.csv", index=False)
# Or write to MySQL — see ds16

Section 6 — Ethics and robots.txt

Check robots.txt

import requests
base = "https://example.com"
robots = requests.get(f"{base}/robots.txt", timeout=10)
print(robots.text)

robots.txt tells crawlers which paths are allowed. Educational projects should stay on allowed paths.

Rate limiting

import time

urls = ["https://example.com/page1", "https://example.com/page2"]
for url in urls:
    r = requests.get(url, timeout=10)
  # process r
    time.sleep(1)  # wait 1 second between requests

Rules of thumb:


Practice

  1. Use pd.read_html on a Wikipedia table; save to CSV.
  2. Write a script that fetches a page, extracts all h2 headings, stores in a one-column DataFrame.
  3. Read a site's robots.txt and note one disallowed path.

Checklist

  • [ ] Can you fetch a page with requests.get and handle errors?
  • [ ] Can you parse HTML with BeautifulSoup find / find_all?
  • [ ] Can you load HTML tables with pd.read_html or manual parsing?
  • [ ] Do you know to check robots.txt and add rate limits?

What's next

Python & SQL — connect to databases when the data lives in MySQL, not on a web page.