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
Requests, responses, URLs, status codes, and a first fetch in Python.
Tags, attributes and the tree: the underlying structure of every page.
BeautifulSoup end to end: the course portal, scraped live into a DataFrame.
CRISP-DM assumes the data is available. Often it is not, because it sits in a web page built for a browser rather than for analysis.
portal.latarak.com, the site hosting these slides, is scraped live in class.
Each is explained again on the slide where it is first used, and all appear in the glossary at the end.
A web address: which server to ask, and which page on it.
e.g. https://portal.latarak.com/calendar
A computer that stores web pages and sends them out when asked.
e.g. the machine behind portal.latarak.com
The program used to read the web: it asks servers for pages and displays them.
e.g. Chrome, Firefox, Safari
The rules browsers and servers use to talk. https is the encrypted version.
e.g. GET /calendar = “please send the calendar page”
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
A three-digit number on every response saying how it went.
e.g. 200 = OK, 404 = not found
The text format web pages are written in: content wrapped in tags.
e.g. <h1>Academic Calendar</h1>
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
An attribute is a name="value" setting inside an opening tag; class is the one that labels elements.
e.g. <table class="cal-table">
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).
A library is ready-made code someone else wrote; import is the line that loads it.
e.g. import requests
A name that holds a value, like a labelled box.
e.g. r = requests.get(URL) puts the response in r
A named piece of work, called with its name and brackets, with inputs inside.
e.g. len(r.text) gives back 30586
Text, written inside quotes.
e.g. "html.parser", "cal-table"
An ordered collection in square brackets; positions count from 0.
e.g. tables[0] is the first table in the list
Code that repeats a block once per item.
e.g. for tr in rows: runs once per table row
Turn text into a structure a program can search.
e.g. HTML text → a tree of elements
The Python library (bs4) that parses HTML and allows the tree to be searched.
e.g. soup = BeautifulSoup(r.text, "html.parser")
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
A method that returns the text inside an element, without the tags.
e.g. td.get_text(strip=True) → 'Registration period'
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.
Prices, listings, directories, records: most of this exists only inside pages.
Scraping reverses this: page → structure → rows.
Tim Berners-Lee publishes “HTML Tags”: 18 elements for the first web pages.
Leonard Richardson writes a parser that tolerates broken HTML.
Beautiful Soup 4 replaces the version 3 line used since 2006.
The current HTML standard is published.
The name comes from a poem in Alice’s Adventures in Wonderland and from “tag soup”, slang for badly structured HTML.
A parser reads text and builds a structure from it. Beautiful Soup turns a web page into a tree of tags that Python can search.
downloads of beautifulsoup4 in September 2026: about 110 every second.
The whole of the first HTML; a modern page uses far more, and often nests them badly.
Built for pages with unclosed or misnested tags, which are common on the real web.
Real pages are rarely valid HTML; a forgiving parser is what makes scraping them practical.
<h1> or a table <table>SourceDownloads: pypistats.org, without mirrors, retrieved 11 Oct 2026; Wikipedia: HTML; Wikipedia: Beautiful Soup
Extracting structured data from pages meant for humans. One site, targeted fields, a table at the end. This course.
Discovering pages by following links at scale, as Google does. Crawlers find; scrapers extract.
Turning text into structure. The step inside scraping where markup (the tags in a page) becomes a searchable tree.
This week covers scraping: one known site, a few pages, and specific fields extracted.
Screen scraping (old term, includes non-web UIs) and data harvesting (scraping at scale, often said disapprovingly).
A scraper is code that must be maintained against a page outside the analyst’s control. Cheaper options are checked first, in this order.
Many portals (PSA, data.gov.ph, Kaggle) publish CSVs. A download takes seconds; a scraper can take hours.
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.
When the data is visible on a page and nowhere else, a scraper is justified.
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.
All six steps, measured on the portal while building this deck: DNS 4 ms, handshake 44 ms, total 263 ms. Every https fetch performs all of these steps.
The response headers show it: server: cloudflare and
via: 1.1 Caddy. Running curl -sI portal.latarak.com/calendar displays them.
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).
This is the complete picture with steps 1–2 and 4 omitted:
requests (the Python library used to fetch pages) handles the connection, and the server side is the site's responsibility. The scraper works at the level of ask → answer.
An SSLError (an encryption problem) is step 2; a timeout (no answer in time) is step 4; a 429 is the edge server requesting a slower rate. Error messages name the hidden layers.
“The Hypertext Transfer Protocol (HTTP) is a stateless application-level protocol for distributed, collaborative, hypertext information systems.”
| Part | In this week’s fetch of the saved calendar page |
|---|---|
| request: a method and a target | GET /static/datasets/ds227-calendar-2026-10-22.html |
| response: a status code | 200: OK |
| response: headers | Content-Type: text/html; charset=utf-8 |
| response: a body | 30,586 characters of HTML |
| stateless | the next request carries no memory of this one |
Source: Fielding, Nottingham & Reschke, eds. (2022), RFC 9110: HTTP Semantics, IETF.
The protocol (the rules
for talking). https = encrypted HTTP. It is preferred.
Which server to ask. One scraper usually stays on one host.
Which page on that server; scrapers usually loop over this part.
Extra
key=value options after ? — filters, pages, versions.
Relative links like /course/ds227 omit the scheme and host, which the code must add back before requesting.
Looping over paths and filtering with query strings allows one scraper to cover a whole site.
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.
| Code | Means | Action |
|---|---|---|
200 | OK | Parse the body |
301/302 | Moved | Follow the new URL |
403 | Forbidden | Access denied; stop |
404 | Not found | Wrong URL; nothing to parse |
429 | Too many requests | Slow down (next week) |
500 | Server error | Server-side fault; retry later |
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 identityThe 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 returnedThe portal answers text/html; charset=utf-8. An API would say
application/json. It is checked before parsing.
Scrapers use GET (read). POST sends data, such as forms and logins. This week uses only GET.
"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.
One holiday from portal.latarak.com/calendar: the exact markup parsed in Part C.
A request returns status 404. What should a scraper do with the response body?
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.
The most harmful scraper error is one that runs successfully on the wrong page.
Check the status code first and the body second.
portal.latarak.com, this course portal. Target: the academic calendar page, a real table of dates relevant to students.
Public pages, no login, clean tables, and the source can be viewed next to the code.
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).
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.
The raw HTML the server sent: exactly what requests receives. If the target data is here, this week's tools suffice.
The live tree after JavaScript ran (JavaScript: code that runs inside the page and can change it after it loads). If data shows here but not in View Source, it was loaded dynamically, which is next week's topic.
Workflow: Inspect to find the tag and class marking the target data, then confirm it exists in View Source before writing any Python.
Open portal.latarak.com/calendar, right-click a date, Inspect. Find the
<table class="cal-table"> above it.
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 librariesimport requests, bs4Python: load the two libraries so the code can use themprint(requests.__version__, …)show each library’s version number. 2.34.2 4.15.0 means both are installed; a newer version is also acceptablerequests fetches. bs4 parses. pandas holds the
result. Three tools, one pipeline.
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 rr.status_code → 200the status code: 200 means OKr.headers["Content-Type"]look up one header by its name, in square brackets: the server says it sent HTMLlen(r.text) → 30586r.text is the whole page as one string; len counts its characters| Attribute | Type | What it is |
|---|---|---|
r.status_code | int | 200, 404…; checked first |
r.text | str | The body decoded to text; the input to BeautifulSoup |
r.content | bytes | The raw bytes, for images, PDFs, files |
r.headers | dict-like | The response's metadata (Content-Type, …) |
r.ok is a shortcut: True for any 2xx
status. r.raise_for_status() turns error codes into errors that stop the program.
r = requests.get(url) → r.raise_for_status() → only then
parse r.text.
r.status_coderTags, 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.
The kind of element; here, a link (a).
The key to look up; here, href.
Read with
tag["href"].
Read with
tag.get_text().
This element is real: the course hub uses it to link to this course. An
element is the whole thing: opening tag, text, closing
</a>. It has a name, attributes, and
text.
tag["href"] reads an attribute; tag.get_text() reads the text.
| Tag | Meaning | Scraper's interest |
|---|---|---|
<a> | Link | Text label + href target |
<table> <tr> <td> <th> | Table, row, cell, header cell | Ready-made rows and columns |
<ul> / <ol> + <li> | List + items | Repeated records without a table |
<div> | Generic block container | The usual container for content |
<span> | Generic inline container | Small labelled values (dates, prices) |
<h1>…<h6> | Headings | Section titles, record names |
<img> | Image | src attribute — the file's URL |
div and span mean nothing by themselves (a block
starts on a new line; inline sits inside a line of text) ; their class indicates what they contain.
The calendar uses table.cal-table; holidays use
ul.holiday-list with span.h-date / span.h-name.
Parents contain children. Finding data means navigating
this tree: "each span.h-date inside each li inside the
ul." This one is the portal's holiday list.
BeautifulSoup converts the flat text back into this tree so that it can be traversed. DOM (Document Object Model) is the browser’s name for it.
Nested folders, where the ul is a folder, each li a folder inside it, and each span a file inside that.
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 labelMany elements can share one, like class="cal-table" on both portal
calendar tables. Suitable for selecting all matching elements.
id — a unique labelMeant to appear once per page, like id="main-content". Suitable for selecting exactly one element.
data-* — machine-readable extrasCustom attributes (data-open="1988") often carry cleaner values than the
visible text.
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.
Trimmed from View Source on /calendar, for comparison with the live page.
"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
Most of a page's markup is not the data but the surrounding interface (menus, headers, footers).
Right-click → Inspect shows the exact tag and class before any code is written.
The more specific the selector (the description of which elements to pick), the less irrelevant content must be cleaned later.
After the break: a working scraper built from these concepts.
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.
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 libraryBeautifulSoup(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 soupsoup.find("title")the first <title> element in the tree.get_text()its text without the tags: the words on the browser tabstrip=Truea keyword argument (an input given by name): trim spaces and line breaks from both ends"html.parser" ships with Python. "lxml" is faster if
installed. Same code either way.
find gives one; find_all gives a listThe difference is the return type: one tag versus a list of tags, which determines whether a loop is possible. The underscore in class_ is required because plain class is a Python keyword.
find returns None when nothing matches, a common source of
AttributeError two lines later.
None…class, for, ifNone.find_all| Target | Use | From <a href="/course/ds227">Knowledge Discovery…</a> |
|---|---|---|
| The visible label | a.get_text() | "Knowledge Discovery in Data" |
| The link target | a["href"] | "/course/ds227" |
| A safe attribute read | a.get("href") | "/course/ds227" or None |
| A missing attribute | a["nope"] | KeyError |
Confusing these is the most common BeautifulSoup error. The text is not an attribute; the attribute is not the text.
.get("href") is preferable when a page might omit the attribute.
KeyError is the error for “no such name here”.
name="value" setting on a tag, e.g. href, read with a["href"]r.status_codeget_text(strip=True) as the defaultFormatted 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'Aug 17' and '\n Aug 17 ' are different strings, so group-bys and joins silently treat them as separate values.
.select() uses CSS selectorsselect() 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”.
Both are equally capable for this week's work. Either may be used, consistently; both appear in published code.
| Move | Call | Portal example |
|---|---|---|
| Down (first match) | tag.find(...) | row → its first td |
| Down (all matches) | tag.find_all(...) | table → every tr |
| Up | tag.find_parent("a") | course title h2 → the card's link |
| Sideways | tag.find_next_sibling() | span.h-date → its span.h-name |
Every found tag is itself searchable: find on a row
searches inside that row only. That scoping is what keeps loops correct. A
parent is the element directly around this one; a
sibling sits next to it under the same parent.
find_parent("a") is used for the course-hub cards in a later slide.
Code calls
soup.find("table", class_="caltable") (typo) then
.find_all("tr"). What happens?
AttributeError on NoneB — 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.
When find can miss, the result is checked for None before use.
assert table is not None right after the find, while prototyping.
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.)
requests.get + status check
BeautifulSoup(r.text)
find the tag + class marking the data
loop → text + attributes → dicts (dictionaries)
DataFrame → CSV, then analyse
Steps 1–2 are boilerplate. Step 3 is investigative work in DevTools. Step 4 is where scrapers differ. Step 5 hands over to pandas, the table library from the Week 1–2 labs.
Fetch → Parse → Locate → Extract → Store applies to every scraper.
raise_for_status() converts an error code into an immediate error at this line, instead of an obscure failure three functions later.
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 changer.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 line200 30586status OK, and the page is 30,586 characters of HTMLDevTools 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 Pythonlen(tables) → 2the list holds two tablescal = tables[0]take the first item: an index is a position number, counted from 0The class name came from right-click → Inspect on the live page.
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 listcal.find(...) searches inside this table only; the other table's headers cannot be included.
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 = []start with an empty list that will collect one result per rowfor tr in cal.find("tbody").find_all("tr"):a loop: run the indented lines once for each body row; tr names the current rowcells = [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 stringszip(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 rows37 rows were collected; rows[0] is the first one, printed in curly brackets as key: value pairsThe 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.
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 namedf.shape → (37, 3)37 rows, 3 columnsdf.head(3)the first 3 rows; ... means pandas hid some columns to fit the screendf.to_csv(…, index=False)save the table as a CSV file; index=False leaves out the 0, 1, 2 row labelsFetch → parse → locate → extract → store, on one screen. This exact script ran while building this deck and produced every output shown.
Linked on the course page as scrape_calendar.py, to be run after class.
pd.read_html finds every <table> in the
HTML and returns a list of DataFrames. When it works, four lines suffice.
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.
<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.
Data is in divs, lists, spans, or attributes, as on most modern sites, including most of this portal.
read_html is tried first; if the list is empty or malformed, BS4 is used.
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.
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.
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-listsmall = li.find("small")this item’s note, or None if it has nonehols.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 NoneNone: recorded as missing instead of crashingA 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.
AttributeError = a value was asked for something it does not have'NoneType' is the type of None: li.find("small") found nothing, and None has no get_textprint linefind can return nothing.get() instead of [], with None checksA recorded missing value is data. A crash halfway through a scrape loses work and leaves a partial table that may be mistaken for a complete one.
If a missing field makes the row meaningless, an explicit error is the honest choice.
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 fileopen("calendar.html").read()open it for reading (the default) and read all its text into htmlA 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.
Same pipeline, new targets. The expected (real) outputs are on the right.
tables[1] is "Breaks & Notable Dates" (Event,
Date). Build its DataFrame. Check: 5 rows; first event is
the UP Cebu CU Anniversary.
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.
Add the holiday lists — all three semesters, with the optional-note fix.
Sites publish crawling rules at /robots.txt. The portal serves one at portal.latarak.com/robots.txt; it is short and recommended reading.
Rapid repeated requests burden a server and result in a 429 or a ban.
time.sleep(1) (pause for one second) between requests is the minimum courtesy.
Terms of service and personal data both constrain what may be collected. Public page ≠ public data.
This week's scraping used explicit permission, public pages, and few requests, which is the model to follow. The full ethics discussion is next week.
Week 4: APIs, dynamic pages, and scraping ethics in full.
<li> is a tag; tag + content + closing tag is an elementname="value" on a tag; class labels elementsul.holiday-list liimport requestsr = requests.get(URL)len(x)rows.append(x)r.status_code"cal-table"[ ] / a position counted from 0for tr in rows:[x for x in …]requests.get(url)None) / a list of every matchstrip=True trims the endsNone if it is missingStatus code first, body second, enforced by raise_for_status().
Inspect finds the class; View Source confirms the server sent it.
Fetch → Parse → Locate → Extract → Store. Tables get the
read_html shortcut.
.get(), None checks, snapshots: pages change over time.
Parse the health-station directory, then scrape the live calendar inside
the portal (~45 min), then repeat it with requests on a personal computer.
BeautifulSoup "Quick Start"; requests "Quickstart"; MDN "What is HTTP?" — linked on the course page.
Summary: scraping converts a tree built for reading into rows built for analysis, with care, because the tree can change.
Extraction is a Data Preparation decision, not free data.
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