与HTMLParser属性混淆

时间:2013-08-03 14:25:30

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

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

我用Google搜索,但找不到答案。在Python 3.x中,类HTMLParser是否拥有它?

1 个答案:

答案 0 :(得分:1)

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

另一方面,Python 3中的html.parser模块在​​Python 2中被称为HTMLParser具有anchorlist属性。< / p>

您可以通过侦听开始标记事件来模拟属性,对于任何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' and 'href' in attrs:
            self.anchorlist.append(attrs['href'])

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