← 中文资源

简体中文版本

html.parser 提取标签与链接

继承 html.parser 收集标题、链接与图片地址,保持流式解析且不依赖第三方库。

阅读英文原文

实现说明

html.parser 提取标签与链接以类 LinkCollector和函数 __init__、handle_starttag、handle_endtag、handle_data为骨架。 从 html 导入了 HTMLParser——导入清单就是这段代码触碰的库表面。

使用要点

  • html 必须先装好——示例直接导入它们。
  • 每一步打印都带着自己的标签:headings:、links:、images:。

常见问题

需要安装第三方包吗?

需要——html。运行前请先加入项目依赖。

主要签名是 def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None

核心语句

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

代码示例

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()