Python Intermediate - Lesson 09 - Responsible Web Data Collection
Python Intermediate · Lesson 09
Responsible Web Data Collection
Python can request a public web page and extract information such as its title or headings. This lesson makes one request to the reserved example domain, then parses the returned HTML.
1. Install the two small libraries
requests handles HTTP connections, and
beautifulsoup4 helps parse HTML. Install them in your Python
environment:
python -m pip install requests beautifulsoup4
This is a one-time setup for that environment. The example uses the standard-library HTML parser that comes with Python.
2. Request one public page
Set a timeout so the program does not wait indefinitely. Check the HTTP
status with raise_for_status() before trying to parse the
response.
import requests
url = "https://example.com/"
headers = {"User-Agent": "PythonLearningDemo/1.0"}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
print(response.status_code)
This makes one request. The user-agent identifies the small learning script; it is not a way to disguise or bypass restrictions.
3. Parse the HTML, not with regex
HTML has a nested structure. Use an HTML parser to select elements rather than trying to match the whole document with a regular expression.
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
page_title = soup.title.get_text(" ", strip=True) if soup.title else "No title"
first_heading = soup.find("h1")
if first_heading:
heading_text = first_heading.get_text(" ", strip=True)
else:
heading_text = "No main heading"
print(page_title)
print(heading_text)
4. Handle request failures
Network requests can fail because a page is unavailable, a connection times out, or the server returns an error. Catch the library’s expected request exception and report it clearly.
import requests
try:
response = requests.get("https://example.com/", timeout=10)
response.raise_for_status()
except requests.RequestException as error:
print(f"Could not retrieve the page: {error}")
Hands-on exercises
-
Write a request to
https://example.com/with a 10-second timeout. Callraise_for_status()before using the response. -
Parse
response.textwith Beautiful Soup. Print the page title and the firsth1, using a fallback message if either is missing.
Show Solution & Common Mistakes
Exercise 1 — one possible solution
import requests
response = requests.get("https://example.com/", timeout=10)
response.raise_for_status()
Exercise 2 — one possible solution
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, "html.parser")
title = soup.title.get_text(" ", strip=True) if soup.title else "No title"
heading = soup.find("h1")
heading_text = (
heading.get_text(" ", strip=True)
if heading
else "No main heading"
)
print(title)
print(heading_text)
Common mistakes:
- Requesting a page without a timeout.
-
Skipping
raise_for_status()and treating an error page as the page you wanted. -
Assuming a page always has a
titleorh1; check for missing elements. - Using regex to parse nested HTML instead of an HTML parser.
- Sending repeated or high-volume requests without permission.
Quick quiz
Choose an answer, then select Check answer.
1. What does response.raise_for_status() do?
2. Why set timeout=10 on a request?
3. What should you use to find an HTML heading?
Mini-project: Public Page Snapshot
Create a small one-page report that retrieves a permitted public page and prints its title, first main heading, and meta description when available.
Requirements:
- Use only the example page
https://example.com/for the first test. - Send one request with an identifying user-agent and a 10-second timeout.
- Check the response status before parsing.
- Extract the title, first
h1, and description if present. - Handle request failures and missing page elements.
Before adapting it to another site: check permission and the site’s terms. Prefer an official API if one is available. Do not use this example to bypass access controls or increase request volume.
Show Full Project Solution
import requests
from bs4 import BeautifulSoup
def main():
url = "https://example.com/"
headers = {"User-Agent": "PythonLearningDemo/1.0"}
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
except requests.RequestException as error:
print(f"Could not retrieve the example page: {error}")
return
soup = BeautifulSoup(response.text, "html.parser")
if soup.title:
title = soup.title.get_text(" ", strip=True)
else:
title = "No title found"
heading = soup.find("h1")
if heading:
heading_text = heading.get_text(" ", strip=True)
else:
heading_text = "No main heading found"
description_tag = soup.find("meta", attrs={"name": "description"})
if description_tag and description_tag.get("content"):
description = description_tag["content"].strip()
else:
description = "No description found"
print(f"Page: {url}")
print(f"Title: {title}")
print(f"Main heading: {heading_text}")
print(f"Description: {description}")
if __name__ == "__main__":
main()
The script makes one request and prints a short summary. It does not follow links or collect a list of pages.
Key takeaways
- Check permissions and prefer an API or downloadable dataset where available.
- Use a timeout and check the response status before parsing HTML.
- Use an HTML parser and handle missing elements and request failures.
- Keep collection narrow, low-volume, and limited to information you are allowed to use.