html.parser Extracts Tags And Links
Subclass html.parser to collect headings, links, and image sources from a page while keeping the parser streaming and dependency free.
Code
from html.parser import HTMLParser
PAGE = '''
<html>
<body>
<h1 id="top">Release notes</h1>
<p>See <a href="/docs/">docs</a> and <a href="https://example.com">site</a>.</p>
<img src="logo.png" alt="logo">
</body>
</html>
'''
class LinkCollector(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.links: list[tuple[str, str]] = []
self.headings: list[str] = []
self.images: list[str] = []
self._in_heading = False
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
values = dict(attrs)
if tag == 'a' and values.get('href'):
self.links.append((values['href'], ''))
if tag == 'img' and values.get('src'):
self.images.append(values['src'])
if tag in {'h1', 'h2'}:
self._in_heading = True
def handle_endtag(self, tag: str) -> None:
if tag in {'h1', 'h2'}:
self._in_heading = False
def handle_data(self, data: str) -> None:
text = data.strip()
if not text:
return
if self._in_heading:
self.headings.append(text)
elif self.links and self.links[-1][1] == '':
href, _ = self.links[-1]
self.links[-1] = (href, text)
def main() -> None:
collector = LinkCollector()
collector.feed(PAGE)
collector.close()
print('headings:', collector.headings)
print('links:', collector.links)
print('images:', collector.images)
if __name__ == '__main__':
main()Inside the snippet
The working surface is the class LinkCollector and the functions __init__, handle_starttag, handle_endtag and handle_data — everything else is wiring.
From html it pulls HTMLParser — the imports name exactly which library surface the snippet touches.
What to watch for
- Plan for an install step:
htmlis a real dependency, resolved by the package manager.
Putting it to use
Entry signature: def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None
Output lines are prefixed (headings:, links:, images:), making each step’s effect easy to spot.
Core lines
def handle_endtag(self, tag: str) -> None:
if tag in {'h1', 'h2'}:
self._in_heading = False
def handle_data(self, data: str) -> None:
text = data.strip()
if not text:
return
if self._in_heading:
self.headings.append(text)
elif self.links and self.links[-1][1] == '':
href, _ = self.links[-1]
self.links[-1] = (href, text)
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.links: list[tuple[str, str]] = []
self.headings: list[str] = []
self.images: list[str] = []
self._in_heading = False
Interactive Tools for This Topic
HTML Entity Encoder / DecoderEncode the five HTML-significant characters and decode named or numeric entities, with optional numeric encoding for non-ASCII text.Markdown Link ExtractorExtract inline and reference-style links from Markdown with titles and definitions resolved into a plain list.Markdown Live PreviewRender Markdown to HTML in real time with a live preview pane. Supports headings, lists, code blocks, links, emphasis, and blockquotes for documentation drafting.
FAQ
- Does this require external packages?
- Yes — `html`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.