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
| Resource | Link |
|---|---|
| Previous | OOP in Python |
| Next | Python & SQL |
| Prerequisites | Pandas basics, Files & exceptions |
| Time | ~50 minutes |
| What you need | pip 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 scraping | Use something else |
|---|---|
| Public price lists, no API | Official API or CSV download |
| One-off research project | Paid data vendor |
| Internal dashboard HTML | read_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 HTMLBreaking it down:
requests.get(url)— HTTP GET requesttimeout=10— don't hang foreverraise_for_status()— fail loudly on errorsresponse.text— HTML as string
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"])| Method | Purpose |
|---|---|
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 ds16Section 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 requestsRules of thumb:
- Add delays between requests (1–2 seconds minimum)
- Identify yourself with a honest User-Agent
- Cache responses locally — don't re-fetch the same page 100 times
- Prefer official APIs and datasets when they exist
Practice
- Use
pd.read_htmlon a Wikipedia table; save to CSV. - Write a script that fetches a page, extracts all
h2headings, stores in a one-column DataFrame. - Read a site's
robots.txtand note one disallowed path.
Checklist
- [ ] Can you fetch a page with
requests.getand handle errors? - [ ] Can you parse HTML with BeautifulSoup
find/find_all? - [ ] Can you load HTML tables with
pd.read_htmlor 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.