Reading data from the web.
Fetch a page, distinguish HTML from data, and select information carefully.
Start here.
A web address, or URL, identifies a resource a server can return. A browser normally requests that resource and displays the response. A Python program can make a similar request. The response body often begins as bytes, which must be decoded into text. An HTML parser then turns markup such as headings and links into a tree of elements that code can search. Fetching, decoding, parsing, and selecting are separate steps with separate possible failures.
In the example, urlopen requests example.com and the with block closes the response afterward. read() gets the response bytes; decode('utf-8') interprets them as text. BeautifulSoup, from the optional beautifulsoup4 package, parses that text as HTML. soup.title finds a title element if one exists. The conditional expression chooses its text or 'No title', so a missing title does not cause an attribute error.
HTML on a public site is presentation, and its structure can change. An official API or data download often gives a clearer data contract. If a page is the only source, choose selectors that express meaning, handle missing elements, and remember that content inserted later by browser JavaScript may not be present in the original response. A web request is also an interaction with another service, so the code should avoid excessive repeated requests and respect the site's access rules.
Build the model.
A web page is delivered as a response, often containing HTML that a browser turns into a document tree. A scraper makes a request, checks the response, parses the document, and extracts the particular information it needs. Each step can fail independently: the network may fail, the server may return an error, or the expected element may not exist.
Before writing selectors, inspect the page's structure and look for a documented API or downloadable data feed. An API usually offers a more stable contract than presentation HTML. If HTML is the only source, select elements by meaningful attributes where possible and expect layout changes. Fetch responsibly: respect access rules, avoid rapid repeated requests, and cache results when the data does not change often.
How it works.
urllib.request can fetch a URL with the standard library. Its response contains bytes; decode them using the declared character set or a known encoding before text parsing. For HTML structure, Beautiful Soup is a common optional parser. It can find elements with CSS selectors, but a selector returning no element gives None, so extraction should check that before reading text.
Write extraction as a function of HTML text. Then you can test it with a saved fixture rather than making a live network request in every test. Keep network retrieval, parsing, and record validation separate. If a price looks like '$12.50', remove the display formatting and convert only after confirming the expected shape. Never treat text from a page as trusted Python code.
Pagination and dynamic pages add more complexity. Some content is loaded later by JavaScript and is absent from the initial HTML response. Inspect the browser's network requests for an official JSON endpoint before reaching for browser automation. If you do automate a browser, wait for specific conditions rather than arbitrary sleeps.
Read it line by line.
from urllib.request import urlopen
from bs4 import BeautifulSoup
with urlopen('https://example.com', timeout=10) as response:
html = response.read().decode('utf-8')
soup = BeautifulSoup(html, 'html.parser')
print(soup.title.get_text(strip=True) if soup.title else 'No title')urlopen makes the request with a timeout. The with block closes the response; read gives bytes, and decode turns them into text. BeautifulSoup creates a navigable tree. soup.title may be absent, so the conditional chooses a safe fallback. This example depends on the optional beautifulsoup4 package and network access; the parsing step also works on saved HTML.
See the rule again.
from bs4 import BeautifulSoup
html = '<html><head><title>Weekly notes</title></head></html>'
soup = BeautifulSoup(html, 'html.parser')
title = soup.select_one('title')
print(title.get_text(strip=True) if title else 'Untitled')The output is Weekly notes. select_one returns the first matching element or None. Keeping a local fixture makes the parsing logic testable even when the source website is unavailable or changes.
A mistake to avoid.
A successful HTTP request does not guarantee useful content. Check the status, encoding, and selector result, and avoid hard-coded positions such as 'the third div' when a meaningful label exists.