Web Scraping
Sometimes the data we want is on a webpage. Web scraping lets us collect it with a program. We’ll download a page, use CSS selectors to find the fields we need, and save them as records we can analyze in Python.
Requests and Responses
A browser gets a webpage by asking a web server for it. A Python program can make the same kind of request. HTTP, the Hypertext Transfer Protocol, defines how that request and the server’s response are exchanged. A response contains a status code describing the outcome and a body containing the requested content. Downloading HTML gives us its source text, before any JavaScript a browser might run.
Use pages provided for downloading or scraping, follow the site’s access rules, and leave time between requests. Saving a page lets us develop the extraction code without requesting it again after every edit.
Create a folder named web-scraping, open it in VS Code, and create and activate its Python environment. Install the two libraries we will use:
python -m pip install requests beautifulsoup4Create download.py:
import requests
url = 'https://csci40.rtealwitter.com/web-scraping/examples/events.html'
response = requests.get(url, timeout=10)
print(response.status_code) # 200 for a successful request
response.raise_for_status()
response.encoding = 'utf-8'
with open('events.html', 'w', encoding='utf-8') as f:
f.write(response.text)Run python download.py, then open events.html in your editor and browser. The event page is also available to save directly.
A successful request usually has status 200. A missing page usually has status 404, while a code in the 500s reports a server error. A server can send an error page as a response, so receiving text does not by itself mean the request succeeded. raise_for_status() raises an exception for an HTTP error before our program writes that text as the requested page. A connection failure or timeout instead raises an exception during requests.get.
response.text is a Python string decoded from the downloaded bytes. Setting response.encoding tells Requests how to decode them, while encoding in open controls how the string is written to disk. Our event page uses UTF-8 for both.
The table below shows how to request a page and inspect its response. (All the cheatsheets from this reading are available as a PDF here.)
| Operation | Purpose |
|---|---|
requests.get(url, timeout=10) |
Request a URL with a limit on waiting for connection or read activity |
response.status_code |
Read the HTTP status number |
response.raise_for_status() |
Raise an exception for an HTTP error |
response.text |
Read the decoded body as a string |
response.content |
Read the body as bytes |
The Requests quickstart documents these operations.
Parsing HTML
A parser reads HTML and builds a tree of its elements. Beautiful Soup lets us work with that tree in Python. We can ask for a particular tag or attribute just as we used selectors to choose elements in CSS.
Our calendar contains three events. The last is cancelled, so it has no duration:
<section class="event">
<a href="/events/moon">Moon <em>Watch</em></a>
<span class="minutes">45 min</span>
</section>
<section class="event">
<a href="/events/meteors">Meteor Workshop</a>
<span class="minutes">30 min</span>
</section>
<section class="event">
<a href="/events/eclipse">Eclipse Talk</a>
<span class="cancelled">Cancelled</span>
</section>
<footer><span class="minutes">Doors open 15 min early</span></footer>Create scrape.py beside events.html:
import bs4
with open('events.html', encoding='utf-8') as f:
html = f.read()
soup = bs4.BeautifulSoup(html, 'html.parser')html is still a string. soup is the parsed document. The import name bs4 means Beautiful Soup 4, and 'html.parser' selects Python’s built-in HTML parser.
Selecting Fields
Beautiful Soup’s select method takes a CSS selector and returns a list of the matching tags in page order. If nothing matches, the list is empty. We can use a loop to visit the matches, or an index to select one of them.
A tag is different from its text. Its .text includes text inside nested elements, while attribute access retrieves information written in the opening tag. Neither operation changes the original HTML. The Beautiful Soup documentation describes these tools.
The table below shows how to select HTML elements and read their contents.
| Operation | Result |
|---|---|
soup.select(selector) |
List of matching tags in document order |
tag.select(selector) |
Matching descendants inside one selected tag |
tag.text |
Text inside a tag, including its nested elements |
tag['href'] |
The value of the required href attribute |
tag.get('title', 'Untitled') |
The attribute value, or the supplied default when absent |
len(matches) |
Number of tags in a list of matches |
Try selecting links from this small HTML string in a separate script:
import bs4
html = '''
<a href="/events/moon">Moon <em>Watch</em></a>
<a href="/events/meteors">Meteor Workshop</a>
<a href="/events/eclipse">Eclipse Talk</a>
'''
soup = bs4.BeautifulSoup(html, 'html.parser')
links = soup.select('a')
print(len(links)) # 3
print(links[0].text) # Moon Watch
print(links[0]['href']) # /events/moon
print(links[0].get('title', 'Untitled')) # Untitled/events/moon is a path on the calendar’s site, not a complete web address. To visit it, the browser combines it with that site’s address.
Extracted text is still a string, even when it contains digits. String operations can remove spaces or units, and numeric conversion makes the result usable in arithmetic. Use int for whole numbers and float for decimal values.
Try this complete example:
import bs4
html = '''
<section class="event"><span class="minutes">45 min</span></section>
<section class="event"><span class="minutes">30 min</span></section>
'''
soup = bs4.BeautifulSoup(html, 'html.parser')
for tag in soup.select('section.event .minutes'):
text = tag.text.strip()
minutes = int(text[:-4])
print(minutes) # 45, then 30 on separate linesThe slice removes the final four characters, ' min'. Adding the strings '45' and '30' would concatenate them. Converting them to numbers allows addition.
Check selection against the page before relying on it. A valid selector can choose the wrong tags without raising an error. A descendant selector reaches through containers, while > requires a direct child. A comma combines selectors and includes each matching tag only once. Adding two Python lists keeps any repeated entries.
Try this complete example:
import bs4
html = '''
<section class="event"><span class="minutes">45 min</span></section>
<section class="event"><span class="minutes">30 min</span></section>
<footer><span class="minutes">Doors open 15 min early</span></footer>
'''
soup = bs4.BeautifulSoup(html, 'html.parser')
print(len(soup.select('.minutes'))) # 3
print(len(soup.select('section.event .minutes'))) # 2
first = soup.select('section.event')[0]
print(first.select('.minutes')[0].text) # 45 minThe broad .minutes selector includes the footer. Searching inside an event restricts the result to that event.
Building Records
A record keeps the fields for one item together. When a page lists many items, select the HTML element for one item at a time, then look for its fields inside that element. This keeps the fields paired correctly even if an item is missing one.
Missing data needs a deliberate choice: keep a record with None, skip it, or stop and investigate. Check a selection before indexing it when an empty result is possible.
Replace scrape.py with this version. It reads the saved events.html page from the first section:
import bs4
with open('events.html', encoding='utf-8') as f:
html = f.read()
soup = bs4.BeautifulSoup(html, 'html.parser')
events = []
for event in soup.select('section.event'):
link = event.select('a')[0]
durations = event.select('.minutes')
minutes = None
if durations:
minutes = int(durations[0].text.strip()[:-4])
events.append({
'name': link.text,
'minutes': minutes,
'href': link['href'],
})
print(events[2]['minutes']) # NoneEach event has a link in this page, so the link selection uses [0] directly. The duration selection is checked because the cancelled event has no duration. To build a list of only scheduled events, use if not durations: continue before constructing the dictionary instead.
Saving and Reading JSON
JSON, JavaScript Object Notation, stores structured values as text. It preserves lists, dictionaries, strings, numbers, and missing values so another program can reconstruct them. Writing records to JSON separates collecting data from analyzing it: the analysis can work from the saved records without downloading or parsing the webpage again.
The table below shows functions for saving and reading JSON.
| Operation | Purpose |
|---|---|
json.dump(data, file, indent=2) |
Write Python data to a file as readable JSON |
json.load(file) |
Read JSON from a file and reconstruct its data |
json.loads(text) |
Parse a string containing JSON; the final s means string |
These functions are in Python’s built-in json module.
This separate example saves three event records as events.json:
import json
events = [
{'name': 'Moon Watch', 'minutes': 45, 'href': '/events/moon'},
{'name': 'Meteor Workshop', 'minutes': 30, 'href': '/events/meteors'},
{'name': 'Eclipse Talk', 'minutes': None, 'href': '/events/eclipse'},
]
with open('events.json', 'w', encoding='utf-8') as f:
json.dump(events, f, indent=2)Run it and open events.json in your editor. The complete scrape.py reads the saved page, extracts its records, and writes the JSON in one program.
Reading a file as ordinary text gives one string. Parsing JSON instead rebuilds its values, so indexing now selects list items or dictionary fields rather than characters. JSON uses null for Python’s None, and quotes distinguish strings from numbers. Parsing does not turn a quoted number into a numeric value.
Create read_events.py:
import json
with open('events.json', encoding='utf-8') as f:
events = json.load(f)
for event in events:
if event['minutes'] is not None:
print(event['name'], event['minutes'])Run python read_events.py after the example that writes events.json. To see the difference between a string and parsed data, try this separately:
import json
text = '[{"minutes": "45"}, {"minutes": 30}, {"minutes": null}]'
data = json.loads(text)
print(text[0]) # [
print(data[0]['minutes'] * 2) # 4545
print(data[1]['minutes'] * 2) # 60
print(data[2]['minutes']) # NoneAn archive may already provide records as JSON, so no HTML extraction is necessary. Once loaded, those records support the same loops, conditions, and string operations as any other Python data.
An observing log records what visitors saw. Save this as observations.json:
[
{"note": "MOON and Saturn"},
{"note": "Clouds, then the moon again"},
{"note": "Saturn's rings"}
]Create read_observations.py:
import json
with open('observations.json', encoding='utf-8') as f:
observations = json.load(f)
count = 0
for observation in observations:
if 'moon' in observation['note'].lower():
count += 1
print(count) # 2Lowercasing makes the comparison ignore capitalization. The condition counts a record once even if it mentions the Moon several times.
Reusable Downloads
Command-line arguments supply values when a program starts, so we can change its inputs without editing its code. The built-in argparse module gives names to these inputs and checks that required values were provided. After parsing, the program uses the resulting values like any other variables.
Create wget.py:
import argparse
import requests
parser = argparse.ArgumentParser()
parser.add_argument('--url', required=True)
parser.add_argument('--filename', required=True)
args = parser.parse_args()
response = requests.get(args.url, timeout=10)
response.raise_for_status()
with open(args.filename, 'wb') as f:
f.write(response.content)
print('Saved', args.filename)Run it with the URL and output filename:
python wget.py --url https://csci40.rtealwitter.com/web-scraping/examples/events.html --filename events.htmlargs.url and args.filename hold strings. The named options can appear in either order. Quote a value containing spaces, such as --filename "night events.html". python wget.py --help displays the available options without downloading anything.
This version writes the downloaded bytes using binary mode, 'wb'. That preserves the original bytes without deciding how to decode them. It is useful for a general downloader that may receive pages using different encodings. To process the saved file as text later, open it with the appropriate encoding.
A required option that is missing produces a usage error before the downloader runs. For a small test, we can pass a list directly to parse_args instead of reading arguments from the terminal.
This example defines its own parser and supplies two named values:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--url', required=True)
parser.add_argument('--filename', required=True)
args = parser.parse_args(['--filename', 'night events.html', '--url', 'https://example.com'])
print(args.filename) # night events.html For several independent downloads, failure on one page does not necessarily prevent processing the rest. Put the request and its status check inside a try block, handle a request error, and use continue to advance to the next page.
Save this as download_many.py:
import requests
pages = [
('https://csci40.rtealwitter.com/missing-page', 'missing.html'),
('https://csci40.rtealwitter.com/web-scraping/examples/events.html', 'events.html'),
]
for url, filename in pages:
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
except requests.exceptions.RequestException:
print('Skipping', url)
continue
with open(filename, 'wb') as f:
f.write(response.content)
print('Saved', filename)Run python download_many.py. The handler skips a missing page and allows the next download to run.