# Standard library: paths
from pathlib import Path
# Web scraping and data
import pandas as pd
import requests
from bs4 import BeautifulSoup<span style="background: #F2A65A; color: #14213D; font-weight: 700; font-size: 13px; padding: 4px 10px; border-radius: 12px;">Module 3 · Data from the Web</span>
<span style="background: #D7E6E4; color: #14213D; font-weight: 600; font-size: 13px; padding: 4px 10px; border-radius: 12px; margin-left: 6px;">⏱ about TODO minutes</span>
Web Scraping 101
| Objective | Scrape a table of race results from a web page and save it as a CSV file. |
| You will | Download a web page with requests · Parse HTML and find tags with BeautifulSoup · Clean table rows into a pandas DataFrame and save it |
| Data | None (the notebook reads a public web page) |
| Core packages | requests · bs4 · pandas |
In this notebook, we are going to go through a simple web scraping example. For this tutorial, we will use a website which has publicly accessible data about a 10K Marathon which happened in 2017 in Oregon, USA. Our target website is this one. On the website, there is data about each Marathon contestant such as how wel they did (place), their name, bib id and more.
Our web scraping task is to extract all this data and save it as CSV file on our computer. We will use two main Python packages for this web scraping task: request and BeatifulSoup. These can be considered as the de facto tools for this task in Python. We will follow the follow hese steps:
- Quickly inspect the website: Since its a straight foward website (the data is in HTML table), we will spend little time here.
- Open the website using request: Here will check a few HTML tags (including table tag(tr)) and inspect their contents.
- Retrieve data from HTML table: This will involve some clean tasks utilising Python built-in String methods
- Create a dataframe and save it to file:
Requirements: requests, beautifulsoup4, pandas.
0. Setup and Configuration
As usual, we import necessary packages/libraries. If you dont have the libraries, the first step would be to install them.
Working Directory and Input Files
# ============================================================
# BASE WORKING DIRECTORIES
# ============================================================
# The course folder is the closest folder, going upwards, that contains environment.yml
DIR_COURSE = next(
(p for p in [Path.cwd(), *Path.cwd().parents] if (p / "environment.yml").exists()), None
)
if DIR_COURSE is None:
DIR_COURSE = Path.cwd()
print("Running outside the course folder (e.g. Colab): upload the datasets to data/raw/.")
DIR_DATA = DIR_COURSE / "data" / "raw"
# ============================================================
# INPUT FILES
# ============================================================
# This notebook reads a web page, not local files.Global Variables for Processing
# ============================================================
# HTML PARSING
# ============================================================
# Parser that BeautifulSoup uses to read HTML
HTML_PARSER = "lxml"Open The Web URL Using Requests
We use the get method to open the URL and then use the text on the response to retrieve the HTML.
url = "https://www.hubertiming.com/results/2017GPTR10K"
response = requests.get(url)
html = response.text
# Lets check if its really an HTML
print(html)Use BeatifulSoup to Parse the HTML
Getting the html of the page is just the first step. Next step is to create a Beautiful Soup object from the html. This is done by passing the html to the BeautifulSoup() function. The Beautiful Soup package is used to parse the html, that is, take the raw html text and break it into Python objects. The second argument lxml is the html parser whose details you do not need to worry about at this point.
# Create BeatifulSoup Object
soup = BeautifulSoup(html, HTML_PARSER)
type(soup)bs4.BeautifulSoup
Extracting Information Using the Soup Object
The soup object allows you to extract interesting information about the website you’re scraping such as getting the title of the page as shown below. For instance, we can get the title of the html. Also, you can get the text of the webpage and quickly print it out to check if it is what you expect.
# Get the title
title = soup.title
print(title)<title>Race results for the 2017 Intel Great Place to Run \ Urban Clash Games!</title>
# Print out the text
text = soup.get_text()
# Note how this is different from the HTML we printed above
print(soup.text)Convert Tabular Information from HTML into a Python DataFrame
Eventually what we would want to do is access a website, extract the information we need and then save it to disk or do some analysis with it. To get there, you should get all table rows in list form first and then convert that list into a dataframe.
# Lets get all table rows and inspect the rows
rows = soup.find_all('tr') # A list of table rows
type(rows)
print(rows[5]) # print only first 5<tr data-bib="814">
<td>1</td>
<td>814</td>
<td>
JARED WILSON
</td>
<td>M</td>
<td>TIGARD</td>
<td>OR</td>
<td>36:21</td>
<td>36:24</td>
<td></td>
</tr>
rows[5]<tr data-bib="814">
<td>1</td>
<td>814</td>
<td>
JARED WILSON
</td>
<td>M</td>
<td>TIGARD</td>
<td>OR</td>
<td>36:21</td>
<td>36:24</td>
<td></td>
</tr>
type(rows[5])# Lets check a single row
for row in rows:
row_td = row.find_all('td')
print(row_td)
type(row_td)[<td>577</td>, <td>443</td>, <td>
LIBBY B MITCHELL
</td>, <td>F</td>, <td>HILLSBORO</td>, <td>OR</td>, <td>1:41:18</td>, <td>1:42:10</td>, <td></td>]
bs4.element.ResultSet
row_td_lst = list(row_td)
type(row_td_lst)list
row_td_lst[0]<td>577</td>
The output above shows that each row is printed with html tags embedded in each row. This is not what we want. We can remove the html tags using Beautiful Soup or regular expressions (not recommended). The easiest way to remove html tags is to use Beautiful Soup, and it takes just one line of code to do this. Pass the string of interest into BeautifulSoup() and use the get_text() method to extract the text without html tags.Lets examine further the one table cell above
# Convert table cell from bs4.element.ResultSet to String
# This step os required because Soup object acceps Strings
# When we want to get text from the HTML tags
str_cells = str(row_td)
print('Its now a string but it has ugly HTML tags')
print()
print(str_cells )
# Now Lets get the text
clean_text = BeautifulSoup(str_cells, HTML_PARSER).get_text()
print()
print('No tags now')
print(clean_text)
# # And Lets see the result
# print(clean_text)Creating a Pandas DataFrame From The Website Data
Now that we know how to extract the text only from HTML tags, we will loop through all rows, get cell contents, use BS to extract text without HTML tags from the cell, do some string cleaning and finally put that row into a list
str_cells = str(cells)
str_cellscleantext = BeautifulSoup(str_cells, HTML_PARSER).get_text()
cleantextcleantext2 = cleantext[1:-1]
cleantext2split_str = cleantext2.split(',')
split_strrowsdef clean_table_row(row=None):
# Extract cell using the cell HTML tag
cells = row.find_all('td')
# Convert to String
str_cells = str(cells)
# Use BS to extract only text and remove HTML tags
cleantext = BeautifulSoup(str_cells, HTML_PARSER).get_text()
# Note that we have brackets at each end, we remove them using list indexing
cleantext2 = cleantext[1:-1]
# This string: cleantext2 is just one whole string, so we split using the delimiter (comma)
split_str = cleantext2.split(',') # returns a list
if len(split_str) > 2:
split_str[2] = split_str[2].strip()
return split_strone_row = rows[10]
print("ROW BEFORE: ")
print(one_row)
print("ROW AFTER: ")
clean_table_row(row=one_row)ROW BEFORE:
<tr data-bib="642">
<td>6</td>
<td>642</td>
<td>
JONATHON TRAN
</td>
<td>M</td>
<td>PORTLAND</td>
<td>OR</td>
<td>39:49</td>
<td>39:55</td>
<td></td>
</tr>
ROW AFTER:
['6',
' 642',
'JONATHON TRAN',
' M',
' PORTLAND',
' OR',
' 39:49',
' 39:55',
' ']
Loop Through All Rows, Clean Them and Put in a List
# We will collect our cleaned rows in this list
cleaned_rows = []
for row in rows:
# Clean up the row using our little function above
clean_row = clean_table_row(row)
#print(clean_row)
# We are only interested in a full table row,
# so discard the rest of the rows using length
if len(clean_row) > 5:
cleaned_rows.append(clean_row)Do some more clean-up
The goal it to remove the \n\n text strings
cleaner_rows = []
for i, row in enumerate(cleaned_rows):
new_row = []
for text in row:
if "\n" in text or "\r" in text:
new_row.append(text.strip())
else:
new_row.append(text)
cleaner_rows.append(new_row)Get Table Headers
We use the same process as above to clean up the headers
# Get Table headers using 'th' HTML tag
headers_with_tags = soup.find_all('th')
# Convert to string
headers_str = str(headers_with_tags)
# Extract text only and leave out HTML tags
headers_without_tags = BeautifulSoup(headers_str, HTML_PARSER).get_text()
headers_without_tags2 = headers_without_tags[1:-1]
# Split using comma delimeter and remove any trailing spaces
split_header = headers_without_tags2.split(',')
split_header2 = [i.strip() for i in split_header]
# Lets check out the headers now
print(split_header2)['Place', 'Bib', 'Name', 'Gender', 'City', 'State', 'Chip Time', 'Gun Time', 'Team']
cleaned_rowsFinally, Lets Create The DataFrame
We have a nested list: cleaned_rows where each element is a list containing a cells of a single table row. We also have column headers. We use these two to create a pandas DataFrame.
# Create Pandas DataFrame
df = pd.DataFrame(data=cleaner_rows, columns=split_header2)
df.head()| Place | Bib | Name | Gender | City | State | Chip Time | Gun Time | Team | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 1 | 814 | JARED WILSON | M | TIGARD | OR | 36:21 | 36:24 | |
| 1 | 2 | 573 | NATHAN A SUSTERSIC | M | PORTLAND | OR | 36:42 | 36:45 | INTEL TEAM F |
| 2 | 3 | 687 | FRANCISCO MAYA | M | PORTLAND | OR | 37:44 | 37:48 | |
| 3 | 4 | 623 | PAUL MORROW | M | BEAVERTON | OR | 38:34 | 38:37 | |
| 4 | 5 | 569 | DEREK G OSBORNE | M | HILLSBORO | OR | 39:21 | 39:24 | INTEL TEAM F |
for idx, row in df.iterrows():
name = row['Name']
if "NICHOLAS" in name:
print(idx)66
df.iloc[66]Place 67
Bib 13
Name NICHOLAS FISCHER
Gender M
City
State
Chip Time 46:41
Gun Time 47:02
Team COLUMBIA TEAM D
Name: 66, dtype: object
Save The DataFrame
Once we are happy with our dataframe, we can save it as a CSV file
## Save AS CSV into data folder
out_file = 'marathoners.csv'
# The index = False option ensures we dont save the default index
df.to_csv(out_file, index=False)EXERCISE
In order to make the exercises easy and fast, I looked for a similar website for you to scrape. The target website also contains Marathon results for men only. The task is the same as in the example, there is a table of Marathon results, please extract the data and save it into a CSV file. A bonus task: for those who finish fast, please tabulate number of participants by country.
Open URL
# Open the website using requests, retrieve HTML and create BS object
url = YOUR CODE
r = YOUR CODE
html = YOUR CODE
bs = BeautifulSoup(html, 'lxml')Extract All Rows and Inspect Them
# Extract all table rows using the tr HTML tag and inspect the first couple of rows
all_rows = YOUR CODE # A list of table rows
print(all_rows[1]) # print only first 5Loop Through Rows, Clean Table Cells and Save Into a List
# Declare list to hold all cleaned rows
cleaned_rows = []
for row in all_rows:
# Extract cell using table cell HTML tag
cells = YOUR CODE
# Extract text only
str_cells = str(cells)
clean_text = BeautifulSoup(str_cells, "lxml").get_text()
# Remove white spaces-a little convuluted but it works
clean_text2 = " ".join(clean_text.split())
# Remove brackts at beginning and end
clean_text3 = clean_text2[1:-1]
# Split clean_text3 using comma delimiter
YOUR CODE
# Remove white spaces again
split_str2 = [i.strip() for i in split_str]
# Add split_str2 to cleaned_rows list
YOUR CODECreate A DataFrame and Inspect It
# Column names: note that the first element of the list contains the column names
# Use list indexing to get the column headers
colnames = YOUR CODE
# Create Dataframe
df_men = pd.DataFrame(data=cleaned_rows[1:], columns=YOUR CODE)# Check the Dataframe
YOUR CODESave the DataFrame to File
# Save into the data folder in the ch1 workig directory
output_filename = YOUR CODE
# save to CSV file
YOUR CODEBonus: Check Number of Men Marathoners by Country
Hint: Use pandas DataFrame value_counts() method for this.
YOUR CODESummary
- TODO
- TODO
- TODO