与HTMLParser attribu混淆

2024-09-30 14:17:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经阅读了html.parser文档,但是我找不到HTMLParser类的anchorlist属性。python2.x有这个属性。在

我在谷歌上搜索,但找不到答案。在python3.x中,HTMLParser类有它吗?在


Tags: 答案文档parser属性htmlpython3python2htmlparser
1条回答
网友
1楼 · 发布于 2024-09-30 14:17:39

anchorlist属性是^{} class的一部分。Python2.6中不推荐使用该模块,Python3中不支持该模块。在

另一方面,python3中的html.parser模块在python2中被称为^{}。它不具有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' and 'href' in attrs:
            self.anchorlist.append(attrs['href'])

或者,使用一个更友好的API,比如BeautifulSoup来收集链接锚。在

相关问题 更多 >