【问题标题】:confused with HTMLParser attribute与 HTMLParser 属性混淆
【发布时间】:2013-08-03 14:25:29
【问题描述】:

我已阅读 html.parser 文档,但我找不到 HTMLParser 类的 anchorlist 属性。 Python 2.x 有这个属性。

我搜索了它,但找不到答案。在 Python 3.x 中,HTMLParser 类有吗?

【问题讨论】:

标签: python python-3.x html-parsing


【解决方案1】:

anchorlist 属性是htmllib.HTMLParser class 的一部分。该模块在 Python 2.6 中已被弃用,并且在 Python 3 中存在。

另一方面,Python 3 中的 html.parser 模块在 Python 2 中称为 HTMLParser。它确实具有 anchorlist 属性。

您可以通过侦听开始标记事件来模拟该属性,对于任何a 标记,将href 属性(如果存在)添加到列表以构建相同的列表:

from html.parser import HTMLParser


class MyHTMLParser(HTMLParser):
    def __init__(self, *args, **kw):
        super().__init__(*args, **kw)
        self.archorlist = []

    def handle_starttag(self, tag, attrs):
        if tag == 'a':
            attributes = dict(attrs)
            if "href" in attributes:
                self.anchorlist.append(attributes["href"])

或者,使用更友好的 API(如 BeautifulSoup)来收集链接锚点。

【讨论】:

  • 我会试试 BeautifulSoup ,感谢您编辑问题
  • handle_starttag 上的 attrs 参数实际上是一个列表而不是字典,因此必须遍历包含具有名称、值的元组的列表,请参阅 docs.python.org/3/library/…
  • @gforcada:确实;将其转换为字典很容易,您不需要期望属性的多个副本。我已经在更新中这样做了。感谢您为我解决此问题!