Mining web pages and mailboxes
How to extract social networks and features from web pages and mailboxes: crawling, parsing, link and text features, building graphs and simple algorithms (TF‑IDF, PageRank), with code examples for HTML and mbox parsing.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Mining web pages and mailboxes turns raw online content into structured data an engineer can analyse. Web pages give hyperlinks and text that define a link graph and topical features; mailboxes (collections of emails) reveal communication networks and sender–recipient ties used in social network analysis and mining.
Key ideas
Start from first principles and simple definitions.
Web page — an electronic document (usually HTML) addressable by a URI/URL transmitted by HTTP/HTTPS. Web pages may contain hyperlinks (anchor tags) that point to other pages.
Mailbox — a stored collection of electronic mail messages in a standard format (examples: mbox, Maildir). Each message has headers (From, To, Cc, Date, Subject) and a body; miners extract header fields to build communication networks.
Crawler (web crawler) — a program that fetches pages starting from seed URLs and follows hyperlinks under rules (robots.txt, politeness). Basic crawler architecture: draw a box labelled "Seed URLs" feeding into "Fetch queue"; arrow to "HTTP fetcher"; arrow to "HTML parser"; parser outputs "new URLs" (back to fetch queue) and "content" (to storage/indexer). Label queue, worker pool, parsers, and storage.
Scraper / parser — code that extracts structured items (text, links, metadata) from HTML or MIME email parts. Scrapers must handle malformed input and character encodings (UTF-8, ISO‑8859‑1).
Link graph (web graph) — a directed graph G = (V, E) where V is the set of pages (URLs) and E contains directed edges (u -> v) when page u has a hyperlink to page v. Represent with an adjacency matrix A where A_{ij} = 1 if edge i->j exists (or a weight for multiple links).
Communication graph (email graph) — a directed (or undirected) graph where nodes are email addresses or users; a directed edge u -> v exists if u sent a message to v. Edge weight often counts the number of messages or totals bytes.
Term frequency – inverse document frequency (TF–IDF) — a numeric weight that reflects how important a word is in a document set. Define:
- term frequency (TF): t_{d,t} = raw count of term t in document d (or normalized by document length).
- inverse document frequency (IDF): idf_t = log(N / df_t) where N is number of documents and df_t is number of documents containing t. TF–IDF = TF × IDF. Give the exact formula in Formulas below and show assumptions (documents independent, idf uses log to dampen effect).
Cosine similarity — a normalized dot product between document TF–IDF vectors used for similarity and clustering.
PageRank — an eigenvector centrality measure for directed graphs. Define PageRank vector r as the stationary distribution of a random surfer with damping factor d (probability of following a random outgoing link), solving r = d·M·r + (1−d)·v where M is the column-stochastic link matrix and v is the teleport (personalization) vector. Explain assumptions: web graph finite, M columns sum to 1 (dangling nodes handled by redistribution). For column-stochastic M, M_{ij} = 1/outdeg(j) if j links to i, else 0.
Building a network from pages or emails: steps an engineer follows
- Acquire data (crawl or export mailbox).
- Preprocess: clean HTML, remove scripts/styles; decode encodings; parse MIME parts in emails.
- Extract artifacts: links (anchor href), anchor text, page title, body text, email headers (From, To, Cc, Date), attachments metadata.
- Normalize entities: canonicalize URLs (scheme, host case, trailing slash), normalize email addresses (lowercase, remove display name), deduplicate.
- Construct graph(s): choose nodes and edge semantics (directed/undirected, weighted/unweighted). Create adjacency list/matrix.
- Compute features: degree, tie strength, TF–IDF, PageRank, reciprocity, temporal patterns.
Ethical and legal notes (short): obey robots.txt, rate limits, do not exfiltrate private mailboxes without consent. These affect how you collect data.
Diagrams to draw in exams (describe exactly):
- Crawler pipeline: rectangular blocks left-to-right: Seeds -> URL queue -> Fetcher pool -> HTML parser -> Storage/Index. Draw arrows and label "robots.txt check" above the queue.
- Email extraction: a vertical flow: Raw mbox file -> split messages -> parse headers -> extract From/To -> build directed edges. Label each step.
Formulas
TF_{d,t} = f_{d,t} where f_{d,t} is the count of term t in document d. (TF = raw count; alternative: normalized TF = f_{d,t} / sum_u f_{d,u})
- TF_{d,t}: number (unitless), applies when representing term frequency.
IDF_t = log(N / df_t) where N = total documents, df_t = number of documents containing term t. log = natural logarithm. (Unitless; applies for IDF weighting; base e or 10 both used—state base if required.)
TFIDF_{d,t} = TF_{d,t} × IDF_t (unitless; document-term weight)
cosine_sim(d1,d2) = (v1 · v2) / (||v1|| · ||v2||) where v1,v2 are TF–IDF vectors (unitless). Applies to measure similarity between documents.
r = d·M·r + (1−d)·v PageRank fixed-point equation. r is PageRank vector (sum to 1), d is damping factor (typical 0.85), M is column-stochastic link matrix, v is teleport vector (usually uniform). Applies when computing PageRank by power iteration. For M, M_{ij} = 1/deg^+(j) if j→i, else 0; dangling columns are replaced by v or redistributed uniformly.
Syntax to remember (Python basic snippets used in examples):
requests.get(url) — fetch HTML content (requires requests).
BeautifulSoup(html, 'html.parser') — parse HTML (requires bs4).
mailbox.mbox(path) — read mbox files (standard library mailbox).
collections.Counter() — count frequencies.
math.log(x) — natural log in Python.
Worked examples
Example 1 — small TF–IDF + cosine similarity from two HTML snippets (Python). Save this as tfidf_example.py and run with Python 3.
Code:
# tfidf_example.py
from bs4 import BeautifulSoup
from collections import Counter
import math
docs_html = [
'<html><head><title>Doc1</title></head><body>Hello world hello mining</body></html>',
'<html><head><title>Doc2</title></head><body>Hello mining web pages</body></html>'
]
# simple tokenizer: lowercase, split on spaces
def text_from_html(h):
soup = BeautifulSoup(h, 'html.parser')
body_text = soup.body.get_text(' ') if soup.body else soup.get_text(' ')
return body_text.lower()
texts = [text_from_html(h) for h in docs_html]
counters = [Counter(t.split()) for t in texts]
N = len(texts)
# compute df
df = Counter()
for c in counters:
for term in c:
df[term] += 1
idf = {term: math.log(N / df[term]) for term in df}
# TF-IDF vectors
vects = []
for c in counters:
vec = {term: (c[term] * idf[term]) for term in df}
vects.append(vec)
# cosine similarity
def dot(a,b):
return sum(a[t]*b[t] for t in df)
def norm(a):
return math.sqrt(sum(x*x for x in a.values()))
v1, v2 = vects
cos = dot(v1,v2) / (norm(v1)*norm(v2))
print('Terms:', sorted(df.keys()))
print('IDF:', {t: round(idf[t],4) for t in sorted(idf)})
print('Cosine similarity: {:.4f}'.format(cos))
Sample input: (none — code uses embedded strings) Sample output (exact):
Terms: ['hello', 'mining', 'pages', 'web', 'world'] IDF: {'hello': 0.0, 'mining': 0.0, 'pages': 0.6931, 'web': 0.6931, 'world': 0.6931} Cosine similarity: 0.0000
Explanation: 'hello' and 'mining' appear in both docs → idf = log(2/2)=0, so only uncommon terms contribute; these do not overlap across the two documents, so the cosine similarity is 0.0000. Note: with N = 2 and idf = log(N / df), any term present in both documents gets zero weight, often making the vectors orthogonal.
Example 2 — parse a tiny mbox-like text to build an adjacency count (Python). Save as mbox_example.py and run.
Code:
# mbox_example.py
from collections import defaultdict
mbox_text = '''From: alice@example.com\nTo: bob@example.com\nSubject: Hi\n\nHello Bob\n---\nFrom: bob@example.com\nTo: alice@example.com, carol@example.com\nSubject: Re\n\nReply\n---\nFrom: dave@example.com\nTo: alice@example.com\nSubject: Intro\n\nHi Alice\n'''
# naive split on message separator '---' for this example
msgs = [m.strip() for m in mbox_text.split('---') if m.strip()]
adj = defaultdict(int)
for m in msgs:
lines = m.split('\n')
hdr = { }
for L in lines:
if ':' in L:
k,v = L.split(':',1)
hdr[k.strip().lower()] = v.strip()
if 'from' in hdr and 'to' in hdr:
sender = hdr['from'].lower()
# split multiple recipients by comma
recipients = [r.strip().lower() for r in hdr['to'].split(',')]
for r in recipients:
adj[(sender,r)] += 1
# print adjacency counts
for (s,r), cnt in sorted(adj.items()):
print(f'{s} -> {r} : {cnt}')
Sample input: (embedded) Sample output (exact):
alice@example.com -> bob@example.com : 1 bob@example.com -> alice@example.com : 1 bob@example.com -> carol@example.com : 1 dave@example.com -> alice@example.com : 1
Explanation: four directed edges counted; multiple recipients generate multiple edges.
Common mistakes
- Using raw term counts for similarity without IDF: common stopwords or repeated words dominate.
- Not parsing email headers correctly: mixing display name and address (e.g., "Alice alice@example.com") without extraction leads to multiple nodes representing same person.
- Ignoring robots.txt and politeness in crawlers (theory vs practice confusion in answers).
For your exam
Question types you will see:
- Definitions: give precise definitions of crawler, mailbox, link graph, TF–IDF, PageRank.
- Short notes: steps to build an email communication network, ethical considerations.
- Derivations: show how PageRank power iteration converges (explain M stochastic, damping factor), derive TF–IDF formula and explain idf role.
- Numericals/programs: compute TF–IDF and cosine similarity for small documents; parse a small mbox and list adjacency counts.
- Diagrams: draw crawler pipeline or email extraction flow (see descriptions above).
What a full-marks answer includes:
- Clear definitions with bolded term names and assumptions.
- Step-by-step algorithmic steps, complexity comments if asked (e.g., PageRank via power iteration O(k·(E+V))).
- For numericals: show intermediate counts (TF, df, idf), plug into formulas and compute final values with units (unitless) and rounding.
- For programs: explain input format, show exact output for given test case.
Quick check
- What header fields in an email are used to build a simple directed communication graph?
- Write the TF–IDF formula and explain what df_t means.
- In PageRank the damping factor d represents what behaviour of the random surfer?
Answers: 1. From and To/Cc (extract senders and recipients). 2. TFIDF_{d,t} = TF_{d,t} × log(N / df_t) ; df_t = number of documents containing term t. 3. d = probability the surfer follows a random outgoing link (1−d is probability of teleporting).
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?