DS 227 · Week 3

Data Scraping I

Web fundamentals and HTML parsing, applied to a live website: this course's own portal is fetched and parsed.

Knowledge Discovery in Data · University of the Philippines Cebu

Outline

Sources of raw data on the web

Key terms · 1 of 2

Nine terms for how the web works

Each is explained again on the slide where it is first used, and all appear in the glossary at the end.

URL

A web address: which server to ask, and which page on it.

e.g. https://portal.latarak.com/calendar

server

A computer that stores web pages and sends them out when asked.

e.g. the machine behind portal.latarak.com

browser

The program used to read the web: it asks servers for pages and displays them.

e.g. Chrome, Firefox, Safari

HTTP

The rules browsers and servers use to talk. https is the encrypted version.

e.g. GET /calendar = “please send the calendar page”

request & response

The request is a program asking for a page; the response is the server’s answer.

e.g. ask for the calendar page → get back 30,586 characters of HTML

status code

A three-digit number on every response saying how it went.

e.g. 200 = OK, 404 = not found

HTML

The text format web pages are written in: content wrapped in tags.

e.g. <h1>Academic Calendar</h1>

tag & element

A tag is a label in angle brackets; an element is the opening tag, its content, and the closing tag.

e.g. <li>Aug 6</li> is one li element

attribute & class

An attribute is a name="value" setting inside an opening tag; class is the one that labels elements.

e.g. <table class="cal-table">

Key terms · 2 of 2

Ten terms for this week’s code

This is the first week with real code on the slides. These are the Python terms it uses (with the same meanings as in DS 208).

library & import

A library is ready-made code someone else wrote; import is the line that loads it.

e.g. import requests

variable

A name that holds a value, like a labelled box.

e.g. r = requests.get(URL) puts the response in r

function & call

A named piece of work, called with its name and brackets, with inputs inside.

e.g. len(r.text) gives back 30586

string

Text, written inside quotes.

e.g. "html.parser", "cal-table"

list

An ordered collection in square brackets; positions count from 0.

e.g. tables[0] is the first table in the list

loop

Code that repeats a block once per item.

e.g. for tr in rows: runs once per table row

parse

Turn text into a structure a program can search.

e.g. HTML text → a tree of elements

BeautifulSoup

The Python library (bs4) that parses HTML and allows the tree to be searched.

e.g. soup = BeautifulSoup(r.text, "html.parser")

find / find_all

find gives the first matching element (or None); find_all gives a list of every match.

e.g. soup.find_all("tr") → every table row

get_text

A method that returns the text inside an element, without the tags.

e.g. td.get_text(strip=True) → 'Registration period'

Previous session

Data must be obtained first

Weeks 1–2 covered the definition and the process. CRISP-DM's first phases, however, require data in hand. Scraping is one way to obtain it when no CSV (a plain-text table file: commas between columns) is provided.

The web as the largest dataset

Prices, listings, directories, records: most of this exists only inside pages.

Designed for reading, not analysis

Scraping reverses this: page → structure → rows.

About the tool

Beautiful Soup was written to read messy web pages

1991

HTML

Tim Berners-Lee publishes “HTML Tags”: 18 elements for the first web pages.

2004

Beautiful Soup

Leonard Richardson writes a parser that tolerates broken HTML.

2012

Version 4

Beautiful Soup 4 replaces the version 3 line used since 2006.

2014

HTML5

The current HTML standard is published.

SourceWikipedia: Beautiful Soup; Wikipedia: HTML

About the tool

How widely Beautiful Soup is used

SourceDownloads: pypistats.org, without mirrors, retrieved 11 Oct 2026; Wikipedia: HTML; Wikipedia: Beautiful Soup

Definitions

Three commonly confused terms

Before writing code

Scraping as the last resort

A scraper is code that must be maintained against a page outside the analyst’s control. Cheaper options are checked first, in this order.

1 · Check for a download

Many portals (PSA, data.gov.ph, Kaggle) publish CSVs. A download takes seconds; a scraper can take hours.

2 · Check for an API

An API is a service a site provides for programs: a request returns structured JSON (a text format for data). It is more stable than any scraper and is next week's topic.

3 · Otherwise, scrape

When the data is visible on a page and nowhere else, a scraper is justified.

Part A

How the web works

One request, one response, repeated billions of times a second.

Weeks 1–2 concerned data already in hand. This part shows how a web page travels to a computer, the first step in collecting data directly.

Version 1 · Complete picture

The steps within a 263-millisecond fetch

1 DNS lookup portal.latarak.com → 104.21.82.229 2 TCP + TLS handshake connection + encryption · ~44 ms 3 HTTP request GET /calendar HTTP/2 + headers 4 The server side (this portal's real chain) Cloudflare edge → Caddy → Gunicorn → Flask → PostgreSQL …builds the HTML, then back out 5 Response travels back 200 OK + headers + 24 kB of HTML 6 Browser renders, or the scraper parses same bytes, different reader
Version 1 · Definitions

Terms in the diagram

These definitions are for reference: they make the diagram, and error messages that mention these terms, readable.

Fetching a page resembles ordering food by phone: look up the number (DNS), dial and agree to talk privately (TCP + TLS), place the order (request), the kitchen cooks it (the server chain), the delivery arrives (response), and it is unpacked (render or parse).

Version 2 · Working model

The client requests; the server responds

Client computer browser / Python Server holds the page GET /calendar → "please send this page" 200 OK + HTML ← "here it is"
Definition

Definition: HTTP

HTTP (RFC 9110)

“The Hypertext Transfer Protocol (HTTP) is a stateless application-level protocol for distributed, collaborative, hypertext information systems.”

PartIn this week’s fetch of the saved calendar page
request: a method and a targetGET /static/datasets/ds227-calendar-2026-10-22.html
response: a status code200: OK
response: headersContent-Type: text/html; charset=utf-8
response: a body30,586 characters of HTML
statelessthe next request carries no memory of this one

Source: Fielding, Nottingham & Reschke, eds. (2022), RFC 9110: HTTP Semantics, IETF.

Definitions · URL

The parts of a URL

https://portal.latarak.com/calendar?v=7
Scheme

The protocol (the rules for talking). https = encrypted HTTP. It is preferred.

Host

Which server to ask. One scraper usually stays on one host.

Path

Which page on that server; scrapers usually loop over this part.

Query string

Extra key=value options after ? — filters, pages, versions.

Status codes

Every response carries a status code

The code is checked before the body (the content itself, after the status and headers) is trusted. A page that "looks empty" is often an unread 404 or 403.

A status code is a courier’s delivery slip: “delivered” (200), “moved, new address attached” (301), “recipient refused” (403), “no such address” (404); the slip is read before the box is opened.

CodeMeansAction
200OKParse the body
301/302MovedFollow the new URL
403ForbiddenAccess denied; stop
404Not foundWrong URL; nothing to parse
429Too many requestsSlow down (next week)
500Server errorServer-side fault; retry later
Definitions · Headers

Requests and responses carry headers

Headers are key–value metadata (labelled facts about the message, like Content-Type: text/html) sent with every request and response. Two are relevant to scrapers from the start.

User-Agent: the requester’s identity

The client’s identity string. Python identifies itself as python-requests/2.34.2 unless configured otherwise. Some sites respond only to browsers.

Content-Type: the format returned

The portal answers text/html; charset=utf-8. An API would say application/json. It is checked before parsing.

GET vs POST

Scrapers use GET (read). POST sends data, such as forms and logins. This week uses only GET.

Response body

The body is HTML text

"View Source" in any browser shows it. It appears disordered, but it is a strict, nested structure that a program can traverse; Part B covers that structure.

Here li marks one item of a list and span marks a small labelled piece of text; class is the label. Part B explains every tag.

<li> <span class="h-date">Aug 6</span> <span class="h-name">Cebu Provincial Charter Day</span> </li>

Real example

One holiday from portal.latarak.com/calendar: the exact markup parsed in Part C.

Review question

Handling a 404 response

A request returns status 404. What should a scraper do with the response body?

A · Parse it anyway
B · Nothing — there's no page to parse
C · Retry immediately forever
D · Treat it as success

B — there is nothing to parse.

A 404 body is usually an error page, not the target data. Parsing it produces invalid rows that appear real. The status is checked before the body.

Example site

Scraping this course portal

portal.latarak.com, this course portal. Target: the academic calendar page, a real table of dates relevant to students.

Suitability as a first target

Public pages, no login, clean tables, and the source can be viewed next to the code.

A permitted target

The instructor runs the site and gives explicit permission to scrape it. It also serves a robots.txt (a file where a site says which pages robots may visit; examined later).

Rule

Public pages only: /calendar and the course hub. Never anything behind a login. These slides fetch a saved copy of /calendar, kept on the portal, so their numbers stay true when the live page changes.

Browser tools

View Source and Inspect are different tools

Setup

Installation on a personal computer

Scraping the open internet requires a personal computer: the in-portal sandbox can reach only this site (which is what the lab uses). One-time setup:

  • pip install …typed in a terminal (a window for typed commands), not in Python: download and install three libraries
  • import requests, bs4Python: load the two libraries so the code can use them
  • print(requests.__version__, …)show each library’s version number. 2.34.2 4.15.0 means both are installed; a newer version is also acceptable
# in your terminal (any one of these) pip install requests beautifulsoup4 pandas # or: uv pip install … / conda install … # check — in python import requests, bs4 print(requests.__version__, bs4.__version__) 2.34.2 4.15.0

Division of labour

requests fetches. bs4 parses. pandas holds the result. Three tools, one pipeline.

First fetch

A first fetch in three lines

This output is real, captured from the live portal while building this deck. The calendar has been edited since, so the live numbers may differ; the frozen snapshot on the course page still gives exactly these.

  • import requestsload the requests library (ready-made code for fetching pages)
  • r = requests.get("https://…")call the function get with the URL as a string: it sends the request and gives back the response, stored in the variable r
  • r.status_code → 200the status code: 200 means OK
  • r.headers["Content-Type"]look up one header by its name, in square brackets: the server says it sent HTML
  • len(r.text) → 30586r.text is the whole page as one string; len counts its characters
import requests URL = ("https://portal.latarak.com/static/datasets/" "ds227-calendar-2026-10-22.html") # a saved copy of /calendar r = requests.get(URL) print(r.status_code) print(r.headers["Content-Type"]) print(len(r.text)) # about 30,000 characters of HTML 200 text/html; charset=utf-8 30586
Reading the response

Four attributes of the response object

AttributeTypeWhat it is
r.status_codeint200, 404…; checked first
r.textstrThe body decoded to text; the input to BeautifulSoup
r.contentbytesThe raw bytes, for images, PDFs, files
r.headersdict-likeThe response's metadata (Content-Type, …)

Definitions

attribute (Python)
a value stored on an object, read with a dot and no brackets: r.status_code
object
a value that carries its own attributes and methods, like the response r
int / str / bytes
a whole number / a string (text) / raw data not yet turned into text
dict-like
works like a dictionary: look a value up by its name, like a phone book
2xx
any status from 200 to 299 — all the “it worked” codes
Part B

HTML structure

Tags, attributes, and the tree they build.

Part A fetched a page as one long string of HTML. This part shows the structure within that string, which determines what to extract from it.

Anatomy

Four parts of an element

<a href="/course/ds227">Knowledge Discovery in Data</a>
Tag name

The kind of element; here, a link (a).

Attribute name

The key to look up; here, href.

Attribute value

Read with tag["href"].

Text content

Read with tag.get_text().

Key terms

Eight tags cover most scraping

TagMeaningScraper's interest
<a>LinkText label + href target
<table> <tr> <td> <th>Table, row, cell, header cellReady-made rows and columns
<ul> / <ol> + <li>List + itemsRepeated records without a table
<div>Generic block containerThe usual container for content
<span>Generic inline containerSmall labelled values (dates, prices)
<h1>…<h6>HeadingsSection titles, record names
<img>Imagesrc attribute — the file's URL
The DOM

Nested tags form a tree

<div> <ul class="holiday-list"> <li> <li> <li> span.h-date span.h-name

Nested folders, where the ul is a folder, each li a folder inside it, and each span a file inside that.

Targeting elements

Classes and ids as selectors

A page has hundreds of <div>s. What makes one findable is its class or id: the labels the site's designers added for their CSS (the style rules that make a page look the way it does).

class — a shared label

Many elements can share one, like class="cal-table" on both portal calendar tables. Suitable for selecting all matching elements.

id — a unique label

Meant to appear once per page, like id="main-content". Suitable for selecting exactly one element.

data-* — machine-readable extras

Custom attributes (data-open="1988") often carry cleaner values than the visible text.

Tables

An HTML table is already a dataset

thead holds the header row; tbody holds data rows; each tr is a row of td cells. The DataFrame (pandas’ table of rows and named columns) structure is already present.

<table class="cal-table"> <thead><tr> <th>Milestone</th> <th>Date</th> <th>Term</th> </tr></thead> <tbody> <tr><td>Registration period (First Semester)</td> <td>Aug 3 – Aug 7, 2026</td><td>1st Sem 2026-2027</td></tr> … </tbody> </table>

Real source

Trimmed from View Source on /calendar, for comparison with the live page.

Locating the data

37 rows within 30,000 characters

"A real page wraps the target values in a hundred irrelevant tags. Scraping consists mostly of finding the one class that marks the data."
The calendar page: ~30,600 characters; the target table: ~5,900 of them
Break

  Ten minutes

After the break: a working scraper built from these concepts.

Part C

Parsing with BeautifulSoup

The library that turns markup back into a searchable tree.

Part B described how a page is built. This part passes its HTML to BeautifulSoup and extracts the required pieces, one Python line at a time.

First step

Text in, tree out

BeautifulSoup receives the HTML string and a parser name, and returns a searchable soup object; no string slicing is needed.

  • from bs4 import BeautifulSoupload only the BeautifulSoup tool from the bs4 library
  • BeautifulSoup(r.text, "html.parser")parse the page text from the fetch, using Python’s built-in HTML reader; the searchable tree goes into the variable soup
  • soup.find("title")the first <title> element in the tree
  • .get_text()its text without the tags: the words on the browser tab
  • strip=Truea keyword argument (an input given by name): trim spaces and line breaks from both ends
from bs4 import BeautifulSoup soup = BeautifulSoup(r.text, "html.parser") print(soup.find("title").get_text()) print(soup.find("h1").get_text(strip=True)) Academic Calendar 2026–2027 - Learning Hub Academic Calendar 2026–2027

Parser choice

"html.parser" ships with Python. "lxml" is faster if installed. Same code either way.

Two core methods

find gives one; find_all gives a list

Definitions

None
Python’s value for “nothing here”
type
the kind of value: one element, a list, a string, None…
keyword (Python)
a word Python reserves for itself, e.g. class, for, if
AttributeError
the error raised when a value is asked for something it does not have, e.g. None.find_all
Common error

Text between tags, data on them

TargetUseFrom <a href="/course/ds227">Knowledge Discovery…</a>
The visible labela.get_text()"Knowledge Discovery in Data"
The link targeta["href"]"/course/ds227"
A safe attribute reada.get("href")"/course/ds227" or None
A missing attributea["nope"]KeyError

Note: “attribute” has three meanings in this course

in a dataset
a column, e.g. barangay (Week 1)
in HTML
a name="value" setting on a tag, e.g. href, read with a["href"]
in Python
a value stored on an object, read with a dot, e.g. r.status_code
Whitespace

get_text(strip=True) as the default

Formatted HTML contains many newlines and much indentation, all of which count as text. strip=True trims the edges before the value is stored.

  • head.get_text()all the text in the table’s header row, including the line breaks from the HTML file
  • '\n …'the quotes mean the value is a string; \n is how Python shows a line break (a newline)
  • head.get_text(strip=True)the same text with the newlines trimmed from both ends; the three headings run together because no separator was asked for
head = cal.find("thead") print(repr(head.get_text())) print(repr(head.get_text(strip=True))) '\nMilestoneDateTerm\n' 'MilestoneDateTerm'

Downstream effect

'Aug 17' and '\n Aug 17 ' are different strings, so group-bys and joins silently treat them as separate values.

Alternative targeting

.select() uses CSS selectors

select() accepts the CSS selector syntax a page uses, which is often shorter than chained find calls. A CSS selector is a short pattern describing which elements to pick: . means class, # means id, a space means “inside”.

# every holiday name on the calendar page names = soup.select("ul.holiday-list span.h-name") print(len(names)) # the one main-content element, by id print(len(soup.select("#main-content"))) # . = class, # = id, space = descendant 24 1

find_all or select

Both are equally capable for this week's work. Either may be used, consistently; both appear in published code.

Tree navigation

Moving from a found element to its relatives

MoveCallPortal example
Down (first match)tag.find(...)row → its first td
Down (all matches)tag.find_all(...)table → every tr
Uptag.find_parent("a")course title h2 → the card's link
Sidewaystag.find_next_sibling()span.h-date → its span.h-name
Review question

Effect of a class-name typo

Code calls soup.find("table", class_="caltable") (typo) then .find_all("tr"). What happens?

A · Returns an empty list
B · AttributeError on None
C · Returns all rows anyway
D · A syntax error

B — None has no .find_all().

find matched nothing, returned None, and calling a method on None raised AttributeError. A typo in a class name causes a failure two lines later than expected.

Worked example · Live

Scraping the portal, end to end

Goal: the academic calendar's "Key Academic Dates" table as a pandas DataFrame, in five steps with real outputs.

Each tool has been introduced separately. This example chains them into one working scraper and explains every line. (The outputs match the frozen snapshot of the page; the live calendar has since grown and changed its columns, so its counts differ.)

Walkthrough · Outline

The five steps of a scraper

1

Fetch

requests.get + status check

2

Parse

BeautifulSoup(r.text)

3

Locate

find the tag + class marking the data

4

Extract

loop → text + attributes → dicts (dictionaries)

5

Store

DataFrame → CSV, then analyse

Walkthrough · Step 1 of 5

Fetch, then check before parsing

raise_for_status() converts an error code into an immediate error at this line, instead of an obscure failure three functions later.

  • three import linesload requests (fetch), BeautifulSoup (parse) and pandas, nicknamed pd (tables)
  • URL = "https://…"a variable holding the address as a string; capitals are a convention for values that never change
  • r.raise_for_status()a method (a function that belongs to a value, after a dot): silent if the status is 2xx, otherwise stops with an error on this line
  • 200 30586status OK, and the page is 30,586 characters of HTML
import requests from bs4 import BeautifulSoup import pandas as pd URL = ("https://portal.latarak.com/static/datasets/" "ds227-calendar-2026-10-22.html") # a saved copy of /calendar r = requests.get(URL) r.raise_for_status() # crashes here if not 2xx print(r.status_code, len(r.text)) 200 30586
Walkthrough · Steps 2–3 of 5

Parse, then locate the table

DevTools identified the class: cal-table. The number of matches is checked before relying on [0]; the page has two such tables.

  • soup.find_all("table", class_="cal-table")a list of every table whose class is cal-table; class_ has an underscore because plain class is reserved by Python
  • len(tables) → 2the list holds two tables
  • cal = tables[0]take the first item: an index is a position number, counted from 0
soup = BeautifulSoup(r.text, "html.parser") tables = soup.find_all("table", class_="cal-table") print(len(tables)) # [0] key dates · [1] breaks & notable dates cal = tables[0] 2

Locating uses Inspect

The class name came from right-click → Inspect on the live page.

Walkthrough · Step 4 of 5

Extract the header row first

Column names come from thead's th cells, collected with a list comprehension (a one-line loop that collects its results into a new list) over find_all.

  • cal.find("thead")inside this table only, the header section
  • .find_all("th")every header cell in it, as a list
  • [th.get_text(strip=True) for th in …]for each cell (called th in turn), take its trimmed text; the square brackets collect the answers into a list
  • the outputa list of 4 strings: the table’s column names
headers = [th.get_text(strip=True) for th in cal.find("thead").find_all("th")] print(headers) ['Milestone', 'Date', 'Term']

Scoped search

cal.find(...) searches inside this table only; the other table's headers cannot be included.

Walkthrough · Step 4 of 5

Body rows into dicts

For each tr: collect its td texts, zip them with the headers, and keep the dict. The next slide explains it line by line.

rows = [] for tr in cal.find("tbody").find_all("tr"): cells = [td.get_text(strip=True) for td in tr.find_all("td")] rows.append(dict(zip(headers, cells))) print(len(rows)) print(rows[0]) 37 {'Milestone': 'Registration period (First Semester)', 'Date': 'Aug 3 – Aug 7, 2026', 'Term': '1st Sem 2026-2027'}
Walkthrough · Step 4, explained

The row loop, one line at a time

  • rows = []start with an empty list that will collect one result per row
  • for tr in cal.find("tbody").find_all("tr"):a loop: run the indented lines once for each body row; tr names the current row
  • cells = [td.get_text(strip=True) for td in tr.find_all("td")]the trimmed text of each cell in this row, as a list of strings
  • zip(headers, cells)pair them up in order: (‘Milestone’, ‘Registration period (First Semester)’), (‘Date’, ‘Aug 3 – Aug 7, 2026’)…
  • dict(…)turn the pairs into a dictionary: key → value pairs, like a phone book (name → number)
  • rows.append(…)append is a list method: add this row’s dictionary to the end of rows
  • the output37 rows were collected; rows[0] is the first one, printed in curly brackets as key: value pairs

The loop works like a clerk copying a paper table onto index cards, writing each cell next to its column name on a new card for every row.

Walkthrough · Step 5 of 5

Storing the result in pandas

A list of dicts converts directly into a DataFrame. From here the pandas methods from the Week 1–2 labs apply: clean, filter, analyse.

  • pd.DataFrame(rows)each dictionary becomes a row; each key becomes a column name
  • df.shape → (37, 3)37 rows, 3 columns
  • df.head(3)the first 3 rows; ... means pandas hid some columns to fit the screen
  • df.to_csv(…, index=False)save the table as a CSV file; index=False leaves out the 0, 1, 2 row labels
df = pd.DataFrame(rows) print(df.shape) print(df.head(3)) df.to_csv("up_calendar.csv", index=False) (37, 3) Milestone ... Term 0 Registration period (First Semester) ... 1st Sem 2026-2027 1 Start of classes (First Semester) ... 1st Sem 2026-2027 2 Change of matriculation deadline (First Semester) ... 1st Sem 2026-2027 [3 rows x 3 columns]
Walkthrough · Complete script

The complete scraper in 14 lines

import requests from bs4 import BeautifulSoup import pandas as pd r = requests.get("https://portal.latarak.com/static/datasets/ds227-calendar-2026-10-22.html") r.raise_for_status() soup = BeautifulSoup(r.text, "html.parser") cal = soup.find_all("table", class_="cal-table")[0] headers = [th.get_text(strip=True) for th in cal.find("thead").find_all("th")] rows = [dict(zip(headers, [td.get_text(strip=True) for td in tr.find_all("td")])) for tr in cal.find("tbody").find_all("tr")] df = pd.DataFrame(rows) df.to_csv("up_calendar.csv", index=False)
Shortcut

Reading pure tables with pandas alone

pd.read_html finds every <table> in the HTML and returns a list of DataFrames. When it works, four lines suffice.

from io import StringIO dfs = pd.read_html(StringIO(r.text)) print(len(dfs)) print(dfs[0].shape) # the same 37 x 3 table, no BeautifulSoup 2 (37, 3)

Common error (pandas ≥ 2.1)

Passing r.text directly is rejected — wrap it in StringIO. A bare string is treated as a file path (a file’s address on disk). StringIO makes text behave like an open file.

Limits of read_html

Most web data is not in a <table>

The portal's holiday list is ul + li + spans. read_html returns nothing for it. Listings, cards, and directories all look like this.

read_html is suitable when…

The data is a genuine HTML table: Wikipedia, PSA tables, sports standings.

BS4 is required when…

Data is in divs, lists, spans, or attributes, as on most modern sites, including most of this portal.

Guideline

read_html is tried first; if the list is empty or malformed, BS4 is used.

Worked example 2

The holiday list: no table

Same page, different structure. Each li holds two labelled spans and sometimes a <small> note (small print). Optional fields are a common cause of scraper failure.

<ul class="holiday-list"> <li><span class="h-date">Aug 6</span><span class="h-name">Cebu Provincial Charter Day <small>UP Cebu only</small></span></li> <li><span class="h-date">Aug 21</span><span class="h-name">Ninoy Aquino Day</span></li> ← no <small> </ul>

Common error

In the 2026 list, exactly 1 of 12 items has the note. Code that assumes the note is present fails on the other 11, and vice versa.

Worked example 2

Handle the optional field explicitly

find("small") returns None when absent, so the code tests for it and stores None as the honest value.

  • soup.select("ul.holiday-list li")every li inside the list with class holiday-list
  • small = li.find("small")this item’s note, or None if it has none
  • hols.append({ … })add a dictionary with two keys, "date" and "note", to the list
  • … if small else Noneif a note was found, use its text; otherwise store None
  • the outputthe first holiday has a note; the second’s note is None: recorded as missing instead of crashing
hols = [] for li in soup.select("ul.holiday-list")[0].find_all("li"): # the 2026 list small = li.find("small") hols.append({ "date": li.find("span", class_="h-date").get_text(strip=True), "note": small.get_text(strip=True) if small else None, }) print(hols[0]) print(hols[1]) {'date': 'Aug 6', 'note': 'UP Cebu only'} {'date': 'Aug 21', 'note': None}
Fragility

Page changes break scrapers

A loop assumes every row has the tags observed during development. If the site is redesigned, or one row differs, the whole loop stops. It happened to this lecture: the calendar was redesigned after it was first written, and its table went from 13 × 4 to 37 × 3.

Reading this error

Last line first
it names the problem: AttributeError = a value was asked for something it does not have
The message
'NoneType' is the type of None: li.find("small") found nothing, and None has no get_text
Line number
the full traceback (the error report) above it says line 2: the print line
Check first
which find can return nothing
# fails on purpose: read the last line for li in holidays: print(li.find("small").get_text()) # 11 of the 12 holidays have no <small>: # the second one stops the loop UP Cebu only AttributeError: 'NoneType' object has no attribute 'get_text'
Defensive extraction

.get() instead of [], with None checks

Reproducibility

Parsing a saved snapshot

Live pages change over time. For homework and debugging, the HTML is saved once and the file is parsed, with the same code from Step 2 onward.

  • open("calendar.html", "w")open a file for writing ("w" erases it first); the name is its file path
  • .write(r.text)write the page’s text into the file
  • open("calendar.html").read()open it for reading (the default) and read all its text into html
# save once open("calendar.html", "w").write(r.text) # parse forever: no network, no drift html = open("calendar.html").read() soup = BeautifulSoup(html, "html.parser") print(soup.find("h1").get_text(strip=True)) Academic Calendar 2026–2027

Frozen copy provided

A snapshot of the calendar page taken this week is linked on the course page; results from it match these slides even if the portal changes.

Exercise · 25 min · Pairs

Exercise: two scrapes

Same pipeline, new targets. The expected (real) outputs are on the right.

Task 1 · The second table

tables[1] is "Breaks & Notable Dates" (Event, Date). Build its DataFrame. Check: 5 rows; first event is the UP Cebu CU Anniversary.

Task 2 · The course hub (harder)

Scrape portal.latarak.com/: every h2.course-title plus the href of its parent link (find_parent("a")). Check: 7 courses; DS 227 is /course/ds227.

Optional extension

Add the holiday lists — all three semesters, with the optional-note fix.

Scraping etiquette

Technical access versus permission

Glossary · 1 of 2

Week 3 terms: the web and HTML

Glossary · 2 of 2

Week 3 terms: Python and BeautifulSoup

Summary + this week's lab

Five main points

Next week

Data scraping II

APIs, dynamic pages, and the ethics of scraping: JSON instead of HTML, pages that build themselves, and what may legitimately be collected.

DS 227 · Knowledge Discovery in Data