Sub topic 3
Extracting links from HTML
A crawler finds new URLs by reading the pages it has already fetched. This chapter covers the extraction step: pulling raw href values out of HTML. It assumes you can read short Python programs and know the basic structure of an HTML page. Resolving and cleaning those values belongs to the next chapter, so extraction only collects them.
Where extraction fits
Why use a real parser
Regular expressions break on real pages. Attributes can use single quotes, double quotes, or no quotes. Tag names can be uppercase. Comments and scripts can contain text that looks like a link. Python's html.parser module tokenizes HTML and tolerates broken markup, so it works on the messy pages a crawler meets.
A minimal extractor
from html.parser import HTMLParser
class LinkExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
def handle_starttag(self, tag, attrs):
if tag == 'a':
for name, value in attrs:
if name == 'href' and value:
self.links.append(value)
parser = LinkExtractor()
parser.feed('<p><a href="/about">About</a> <a href="https://example.org/">Org</a></p>')
print(parser.links) # ['/about', 'https://example.org/']The parser lowercases tag and attribute names for you. An attribute with no value, as in <a href>, arrives as None, so the and value check skips it.
Relative links and the base tag
An href such as intro.html has no meaning without a page to anchor it. You resolve it with urljoin against the page's URL. A page can also declare a <base href> tag, which changes the anchor for every link on it. Because the <base> tag may appear after some links, collect everything first and resolve afterward.
from html.parser import HTMLParser
from urllib.parse import urljoin
class LinkExtractor(HTMLParser):
def __init__(self):
super().__init__()
self.links = []
self.base = None
def handle_starttag(self, tag, attrs):
attrs = dict(attrs)
if tag == 'base' and self.base is None and attrs.get('href'):
self.base = attrs['href']
elif tag == 'a' and attrs.get('href'):
rel = (attrs.get('rel') or '').lower().split()
if 'nofollow' not in rel:
self.links.append(attrs['href'].strip())
page = 'https://example.com/docs/index.html'
html = '''<base href="/files/">
<a href="intro.html">Intro</a>
<a href="mailto:[email protected]">Mail</a>
<a href="/x" rel="nofollow">Skip</a>
<a href="#top">Top</a>'''
parser = LinkExtractor()
parser.feed(html)
root = urljoin(page, parser.base) if parser.base else page
print([urljoin(root, href) for href in parser.links])This prints ['https://example.com/files/intro.html', 'mailto:[email protected]', 'https://example.com/files/#top']. The mailto: link and the fragment still need to be handled, and the normalization step does that.
Common errors
- Resolving against the page URL when the page has a
<base>tag. Every relative link then points to the wrong place. - Forgetting
strip(). Hand-written HTML often has whitespace or newlines insidehrefvalues. - Keeping non-web schemes such as
mailto:,javascript:, andtel:. Filter these out before they reach the frontier. - Treating
rel="nofollow"as a rule. It is a hint from the site owner. Whether you honor it is a policy choice, so decide it deliberately. - Reading only
<a>tags. Frames, image maps, and sitemaps link to pages too. Add them only if your goals need them.
Exercise
The second extractor stores raw href values and calls urljoin only after feed() finishes. Why not resolve each link as soon as it is found?
Show answer
A <base href> tag can appear after some of the links. Resolving early would use the wrong anchor for those links. Collecting raw values first lets the crawler know the final base before it resolves any of them.
Exercise
Name two kinds of href values an extractor should drop or ignore before queuing URLs.
Show answer
Any two of: links with schemes other than http and https (mailto:, javascript:, tel:), empty href values, and fragment-only links such as #top, which point back to the same page.