from dsc80_utils import *
Lecture 10 – Web Scraping¶
Agenda 📆¶
- Review: Accessing HTML.
- HTML basics.
- Parsing HTML using BeautifulSoup.
- Example: Scraping quotes.
- Example: Scraping the HDSI faculty page.
Review: Accessing HTML¶
Making requests¶
Goal: Access information about HDSI faculty members from the HDSI Faculty page.
Let's start by making a GET request to the HDSI Faculty page and see what the resulting HTML looks like.
import requests
fac_response = requests.get('https://datascience.ucsd.edu/faculty/', verify=False)
fac_response
fac_text = fac_response.text
len(fac_text)
print(fac_text[:1000])
Wow, that is gross looking! 😰
- It is raw HTML, which web browsers use to display websites.
- The information we are looking for – faculty information – is in there somewhere, but we have to search for it and extract it, which we wouldn't have to do if we had an API.
- We'll now look at how HTML documents are structured and how to extract information from them.
Best practices for scraping¶
- Send requests slowly and be upfront about what you are doing!
- Respect the policy published in the page's
robots.txtfile.- Many sites have a
robots.txtfile in their root directory, which contains a policy that allows or disallows automatic access to their site. - If there isn't one, like in Project 3, use a 0.5 second delay between requests.
- Many sites have a
- Don't spoof your User-agent (i.e. don't try to trick the server into thinking you are a person).
- Read the Terms of Service for the site and follow it.
Consequences of irresponsible scraping¶
If you make too many requests:
- The server may block your IP Address.
- You may take down the website.
- A journalist scraped and accidentally took down the Cook County Inmate Locater.
- As a result, inmate's families weren't able to contact them while the site was down.
Summary: APIs vs. scraping¶
- APIs are made by organizations that host data.
- For example, X (formally known as Twitter) has an API.
- APIs provide a code-friendly way to access data.
- Usually, APIs give us back data as JSON objects.
- Scraping is the act of emulating a web browser to access its source code.
- As you'll see in Lab 5, it's not technically supported by most organizations.
- When scraping, you get back data as HTML and have to parse that HTML to extract the information you want.
The anatomy of HTML documents¶
What is HTML?¶
- HTML (HyperText Markup Language) is the basic building block of the internet.
- It defines the content and layout of a webpage, and as such, it is what you get back when you scrape a webpage.
- See this tutorial for more details.
For instance, here's the content of a very basic webpage.
!cat data/lec10_ex1.html
Using IPython.display.HTML, we can render it directly in our notebook.
from IPython.display import HTML
HTML(filename=Path('data') / 'lec10_ex1.html')
The anatomy of HTML documents¶
HTML document: The totality of markup that makes up a webpage.
Document Object Model (DOM): The internal representation of an HTML document as a hierarchical tree structure.
HTML element: An object in the DOM, such as a paragraph, header, or title.
HTML tags: Markers that denote the start and end of an element, such as
<p>and</p>.

Useful tags to know¶
| Element | Description |
|---|---|
<html> |
the document |
<head> |
the header |
<body> |
the body |
<div> |
a logical division of the document |
<span> |
an inline logical division |
<p> |
a paragraph |
<a> |
an anchor (hyperlink) |
<h1>, <h2>, ... |
header(s) |
<img> |
an image |
There are many, many more, but these are by far the most common. See this article for examples.
Example: Images and hyperlinks¶
Tags can have attributes, which further specify how to display information on a webpage.
For instance, <img> tags have src and alt attributes (among others):
<img src="king-selfie.png" alt="A photograph of King Triton." width=500>
Hyperlinks have href attributes:
Click <a href="https://example.com/">this link</a> to see an example.
What do you think this webpage looks like?
!cat data/lec10_ex2.html
The <div> tag¶
<div style="background-color:lightblue">
<h3>This is a heading</h3>
<p>This is a paragraph.</p>
</div>
The
<div>tag defines a division or a "section" of an HTML document.- Think of a
<div>as a "cell" in a Jupyter Notebook.
- Think of a
The
<div>element is often used as a container for other HTML elements to style them with CSS or to perform operations involving them using JavaScript.<div>elements often have attributes, which are important when scraping!
Document trees¶
Under the document object model (DOM), HTML documents are trees. In DOM trees, child nodes are ordered.
What does the DOM tree look like for this document?

Parsing HTML using Beautiful Soup¶
Beautiful Soup 🍜¶
- Beautiful Soup 4 is a Python HTML parser.
- To "parse" means to "extract meaning from a sequence of symbols".
- Warning: Beautiful Soup 4 and Beautiful Soup 3 work differently, so make sure you are using and looking at documentation for Beautiful Soup 4.
Example HTML document¶
To start, we'll work with the source code for an HTML page with the DOM tree shown below:

The string html_string contains an HTML "document".
html_string = '''
<html>
<body>
<div id="content">
<h1>Heading here</h1>
<p>My First paragraph</p>
<p>My <em>second</em> paragraph</p>
<hr>
</div>
<div id="nav">
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
</div>
</body>
</html>
'''.strip()
HTML(html_string)
BeautifulSoup objects¶
bs4.BeautifulSoup takes in a string or file-like object representing HTML (markup) and returns a parsed document.
import bs4
bs4.BeautifulSoup?
Normally, we pass the result of a GET request to bs4.BeautifulSoup, but here we will pass our hand-crafted html_string.
soup = bs4.BeautifulSoup(html_string)
soup
type(soup)
BeautifulSoup objects have several useful attributes, e.g. text:
print(soup.text)
Traversing through descendants¶
The descendants attribute traverses a BeautifulSoup tree using depth-first traversal.
Why depth-first? Elements closer to one another on a page are more likely to be related than elements further away.

soup.descendants
for child in soup.descendants:
# print(child) # What would happen if we ran this instead?
if isinstance(child, str):
continue
print(child.name)
Finding elements in a tree¶
Practically speaking, you will not use the descendants attribute (or the related children attribute) directly very often. Instead, you will use the following methods:
soup.find(tag), which finds the first instance of a tag (the first one on the page, i.e. the first one that DFS sees).- More general:
soup.find(name=None, attrs={}, recursive=True, text=None, **kwargs).
- More general:
soup.find_all(tag)will find all instances of a tag.
find finds tags!
soup.find('div')

Let's try and find the <div> element that has an id attribute equal to 'nav'.
soup.find('div', attrs={'id': 'nav'})
find will return the first occurrence of a tag, regardless of its depth in the tree.
# The ul child is not at the top of the tree, but we can still find it.
soup.find('ul')
Using find_all¶
find_all returns a list of all matches.
soup.find_all('div')
soup.find_all('li')
[x.text for x in soup.find_all('li')]
Node attributes¶
- The
textattribute of a tag element gets the text between the opening and closing tags. - The
attrsattribute of a tag element lists all of its attributes. - The
getmethod of a tag element gets the value of an attribute.
soup.find('p')
soup.find('p').text
soup.find('div')
soup.find('div').text
soup.find('div').attrs
soup.find('div').get('id')
The get method must be called directly on the node that contains the attribute you're looking for.
soup
# While there are multiple 'id' attributes, none of them are in the <html> tag at the top.
soup.get('id')
soup.find('div').get('id')
Question 🤔
Consider the following HTML document, which represents a webpage containing the top few songs with the most streams on Spotify today in Canada.
<head>
<title>3*Canada-2022-06-04</title>
</head>
<body>
<h1>Spotify Top 3 - Canada</h1>
<table>
<tr class='heading'>
<th>Rank</th>
<th>Artist(s)</th>
<th>Song</th>
</tr>
<tr class=1>
<td>1</td>
<td>Harry Styles</td>
<td>As It Was</td>
</tr>
<tr class=2>
<td>2</td>
<td>Jack Harlow</td>
<td>First Class</td>
</tr>
<tr class=3>
<td>3</td>
<td>Kendrick Lamar</td>
<td>N95</td>
</tr>
</table>
</body>
Part 1: How many leaf nodes are there in the DOM tree of the previous document — that is, how many nodes have no children?
Part 2: What does the following line of code evaluate to?
len(soup.find_all("td"))
Part 3: What does the following line of code evaluate to?
soup.find("tr").get("class")
Example: Scraping quotes¶
Example: Scraping quotes¶
Consider quotes.toscrape.com.

Goal: Extract quotes (and relevant metadata) into a DataFrame.
Specifically, let's try to make a DataFrame that looks like the one below:
| quote | author | author_url | tags | |
|---|---|---|---|---|
| 0 | “The world as we have created it is a process of our thinking. It cannot be changed without changing our thinking.” | Albert Einstein | https://quotes.toscrape.com/author/Albert-Einstein | change,deep-thoughts,thinking,world |
| 1 | “It is our choices, Harry, that show what we truly are, far more than our abilities.” | J.K. Rowling | https://quotes.toscrape.com/author/J-K-Rowling | abilities,choices |
| 2 | “There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.” | Albert Einstein | https://quotes.toscrape.com/author/Albert-Einstein | inspirational,life,live,miracle,miracles |
Question 🤔
Ask an LLM to write code to scrape the first ten pages of quotes from https://quotes.toscrape.com/ into a DataFrame called quotes_llm. The first three rows of quotes_llm should have the three quotes above. The last row of quotes_llm should contain a quote from George R.R. Martin.
After having an LLM write code, paste it below and see if it works. If it doesn't work, try to adjust your prompt until it does. Once you have something that works, submit your final prompt and generated code.
The plan¶
Eventually, we will create a single function – make_quote_df – which takes in an integer n and returns a DataFrame with the quotes on the first n pages of quotes.toscrape.com.
To do this, we will define several helper functions:
download_page(i), which downloads a single page (pagei) and returns aBeautifulSoupobject of the response.process_quote(div), which takes in a<div>tree corresponding to a single quote and returns a dictionary containing all of the relevant information for that quote.process_page(divs), which takes in a list of<div>trees corresponding to a single page and returns a DataFrame containing all of the relevant information for all quotes on that page.
Key principle: some of our helper functions will make requests, and others will parse, but none will do both!
- Easier to debug and catch errors.
- Avoids unnecessary requests.
Downloading a single page¶
def download_page(i):
url = f'https://quotes.toscrape.com/page/{i}'
request = requests.get(url)
return bs4.BeautifulSoup(request.text)
In make_quote_df, we will call download_page repeatedly – once for i=1, once for i=2, ..., i=n. For now, we will work with just page 1 (chosen arbitrarily).
soup = download_page(1)
Parsing a single page¶
Let's look at the page's source code (right click the page and click "Inspect" in Chrome) to find where the quotes in the page are located.
divs = soup.find_all('div', class_='quote')
# Shortcut for the following, just for when the attribute key is class:
# divs = soup.find_all('div', attrs={'class': 'quote'})
divs[0]
From this <div>, we can extract the quote, author name, author's URL, and tags.
divs[0]
# The quote.
divs[0].find('span', class_='text').text
# The author.
divs[0].find('small', class_='author').text
# The URL for the author.
divs[0].find('a').get('href')
# The quote's tags.
divs[0].find('meta', class_='keywords').get('content')
Let's implement our next function, process_quote, which takes in a <div> corresponding to a single quote and returns a dictionary containing the quote's information.
Why use a dictionary? Passing pd.DataFrame a list of dictionaries is an easy way to create a DataFrame.
def process_quote(div):
quote = div.find('span', class_='text').text
author = div.find('small', class_='author').text
author_url = 'https://quotes.toscrape.com' + div.find('a').get('href')
tags = div.find('meta', class_='keywords').get('content')
return {'quote': quote, 'author': author, 'author_url': author_url, 'tags': tags}
process_quote(divs[-1])
Our last helper function will take in a list of <div>s, call process_quote on each <div> in the list, and return a DataFrame.
def process_page(divs):
return pd.DataFrame([process_quote(div) for div in divs])
process_page(divs)
Putting it all together¶
def make_quote_df(n):
'''Returns a DataFrame containing the quotes on the first n pages of https://quotes.toscrape.com/.'''
dfs = []
for i in range(1, n+1):
# Download page n and create a BeautifulSoup object.
soup = download_page(i)
# Create DataFrame using the information in that page.
divs = soup.find_all('div', class_='quote')
df = process_page(divs)
# Append DataFrame to dfs.
dfs.append(df)
# Stitch all DataFrames together.
return pd.concat(dfs).reset_index(drop=True)
quotes = make_quote_df(3)
quotes.head()
quotes[quotes['author'] == 'Albert Einstein']
The elements in the 'tags' column are all strings, but they look like lists. This is not ideal, as we will see shortly.
Example: Scraping the HDSI faculty page¶
Example: Scraping the HDSI faculty page¶
Let's try and extract a list of HDSI Faculty from datascience.ucsd.edu/faculty.
- As usual, we start by opening the page, right clicking somewhere on the page, and clicking "Inspect" in Chrome.
- As we can see, the HTML is much more complicated – this is usually the case for websites in the wild.
fac_response = requests.get('https://datascience.ucsd.edu/faculty/', verify=False)
fac_response
soup = bs4.BeautifulSoup(fac_response.text)
It's not easy identifying which <div>s we want. The Inspect tool makes this easier, but it's good to verify that find_all is finding the right number of elements.
divs = soup.find_all(
class_='vc_grid-item',
)
len(divs)
Within here, we need to extract each faculty member's name. It seems like names are stored as text within the <h4> tag.
divs[0]
divs[0].find('h4').text
We can also extract job titles:
divs[0].find(class_='field').text
Let's create a DataFrame consisting of names and job titles for each faculty member.
names = [div.find('h4').text for div in divs]
names[:10]
titles = [div.find(class_='field').text for div in divs]
titles[:10]
faculty = pd.DataFrame({
'name': names,
'title': titles,
})
faculty.head()
Now we have a DataFrame!
faculty[faculty['title'].str.contains('Teaching') | faculty['title'].str.contains('Lecturer')]
What if we want to get faculty members' pictures?
from IPython.display import Image, display
def show_picture(name):
idx = faculty[faculty['name'].str.lower().str.contains(name.lower())].index[0]
display(Image(url=divs[idx].find('img')['src'], width=200, height=200))
show_picture('marina')
Question 🤔
Consider the following HTML document, which represents a webpage containing the top few songs with the most streams on Spotify today in Canada.
<head>
<title>3*Canada-2022-06-04</title>
</head>
<body>
<h1>Spotify Top 3 - Canada</h1>
<table>
<tr class='heading'>
<th>Rank</th>
<th>Artist(s)</th>
<th>Song</th>
</tr>
<tr class=1>
<td>1</td>
<td>Harry Styles</td>
<td>As It Was</td>
</tr>
<tr class=2>
<td>2</td>
<td>Jack Harlow</td>
<td>First Class</td>
</tr>
<tr class=3>
<td>3</td>
<td>Kendrick Lamar</td>
<td>N95</td>
</tr>
</table>
</body>
Part 4: Complete the implementation of the function top_nth, which takes in a positive integer n and returns the name of the n-th ranked song in the HTML document. For instance, top_nth(2) should evaluate to "First Class" (n=1 corresponds to the top song).
Note: Your implementation should work in the case that the page contains more than 3 songs.
def top_nth(n):
return soup.find("tr", attrs=__(a)__).find_all("td")__(b)__
Web data in practice¶
The spread of true and false news online by Vosoughi et al. compared how true and false news spreads via Twitter:
There is worldwide concern over false news and the possibility that it can influence political, economic, and social well-being. To understand how false news spreads, Vosoughi et al. used a data set of rumor cascades on Twitter from 2006 to 2017. About 126,000 rumors were spread by ∼3 million people. False news reached more people than the truth; the top 1% of false news cascades diffused to between 1000 and 100,000 people, whereas the truth rarely diffused to more than 1000 people. Falsehood also diffused faster than the truth. The degree of novelty and the emotional reactions of recipients may be responsible for the differences observed.
To conduct this study, the authors used the Twitter API for accessing tweets and web-scraped fact-checking websites to verify whether news was false or not.
Summary, next time¶
- Beautiful Soup is an HTML parser that allows us to (somewhat) easily extract information from HTML documents.
soup.findandsoup.find_allare the functions you will use most often.
- When writing scraping code:
- Use "inspect element" to identify the names of tags and attributes that are relevant to the information you want to extract.
- Separate your logic for making requests and for parsing.
Next time¶
Regular expressions!