Sub topic 4
Parsing HTML and extracting links
This chapter assumes you can read short Python snippets and know what an HTML <a> tag and an HTTP response are. It covers the step between fetching a page and deciding what to fetch next. That step turns raw HTML into a list of candidate URLs.
Why parsing matters
A fetched page is just text. The crawler needs to find the links in it, and a regular expression over the raw text is fragile. Real HTML has unquoted attributes, mixed case, comments, and tags split across lines. A parser reads the markup the way a browser does, so it ignores links inside comments and handles odd formatting.
Python's standard library includes html.parser.HTMLParser. It calls a method each time it sees a start tag, and you override that method to collect what you need.
Extracting and resolving links
The href value is often relative, such as docs/page.html or /guide. It only makes sense relative to the URL of the page that contained it. urljoin does that resolution. urldefrag removes the #fragment, because a fragment points inside a page and does not name a different document.
from html.parser import HTMLParser
from urllib.parse import urljoin, urldefrag, urlparse
class LinkParser(HTMLParser):
def __init__(self):
super().__init__()
self.links = [] # list of (href, rel_values)
def handle_starttag(self, tag, attrs):
if tag != "a":
return
attrs = dict(attrs)
href = attrs.get("href")
if href:
rel = (attrs.get("rel") or "").lower().split()
self.links.append((href, rel))
def extract_links(base_url, html):
parser = LinkParser()
parser.feed(html)
results = []
for href, rel in parser.links:
absolute, _ = urldefrag(urljoin(base_url, href))
if urlparse(absolute).scheme in ("http", "https"):
results.append((absolute, "nofollow" in rel))
return results
html = """
<a href="/guide#intro">Guide</a>
<a href="docs/page.html">Docs</a>
<a href="mailto:[email protected]">Mail</a>
<a href="https://other.example/x" rel="nofollow ugc">Other</a>
<a>No href</a>
"""
for link in extract_links("https://example.com/blog/post.html", html):
print(link)This prints:
('https://example.com/guide', False)
('https://example.com/blog/docs/page.html', False)
('https://other.example/x', True)The mailto: link is dropped by the scheme check. The anchor with no href is dropped because there is nothing to follow. The second value in each tuple records whether the link carried rel="nofollow".
Common errors
- Resolving against the wrong base. Use the final URL after redirects, not the one you requested. If the page contains a
<base href>tag, that value overrides the page URL as the base. - Keeping fragments.
/guide#introand/guide#setupare the same document. Withouturldefrag, you fetch it twice. - Treating every
hrefas a web page. Links such asjavascript:void(0),tel:, andmailto:are not fetchable pages. Filter by scheme. - Ignoring
rel.relcan hold several space-separated values, so test membership in a list rather than comparing the whole string. - Decoding failures. Bytes that are not valid UTF-8 can raise errors. Decode with
errors="replace"so one bad byte does not lose the page.
What happens next
The output is a list of candidate URLs, not a list of pages to fetch. Each one still needs normalization, deduplication, and a robots.txt check before it enters the crawl frontier. A nofollow flag is a hint that the site does not vouch for the target. Engines treat it as a signal and do not always ignore the link.
Exercise
A page at https://example.com/a/b/index.html contains <a href="../c.html#top">. What absolute URL should the crawler record, and why is the fragment removed?
Show answer
The crawler records https://example.com/a/c.html. The .. moves up one directory from /a/b/ to /a/, and the fragment #top is removed because it points inside the page and does not identify a different document. Keeping it would make the crawler treat the same page as several URLs.