首页 > 解决方案 > 在 Python 中使用 HTMLParser 提取超链接 URL 和内容

问题描述

我正在尝试将我的维基百科监视列表转换为可读的降价格式文档。为此,我使用 Python 的html内置模块从他们的网站解析本地保存的 html。到目前为止,我制作了一个脚本来提取所有相关链接,但我未能在输出中包含它们的内容(引理名称)。还尝试handle_starttag为数据实现另一个,但我无法正确过滤以仅包含<a>监视列表项的标签。

这是我到目前为止的进展

import html
from html.parser import HTMLParser

with open(r'data/Edit watchlist - Wikipedia.html', "r") as f:
    page = f.read()

class Parse(HTMLParser):
    def __init__(self):
        super().__init__()
        self.reset()

    def handle_starttag(self, tag, attrs):
        if tag == "a":
           for name, link in attrs:
               if (name == "href" and 
                   "Talk:" not in link and 
                   "Special:" not in link and 
                   "Help:" not in link and
                   "Wikipedia:" not in link and
                   "index.php" not in link and
                   link.startswith("http")):
                   print (link)
 
p = Parse()
p.feed(page)

标签: pythonhtmlparsing

解决方案


推荐阅读