解析网页以输入 Telegram Telegraph create_page

Parse webpage to feed into Telegram Telegraph create_page

我制作了一个 Telegram 机器人,它通过 Telegram 的“Telegraph”服务提供网页,这样我就可以阅读即时加载的页面。

因此,我可以节省移动数据流量并在途中放下烦人的广告。

因此,我需要一种方法将任何网页提供给 this library 的 createPage 方法。

问题是网页可以包含任何标签,而 Telegraph 只支持这些 Html 标签。

ALLOWED_TAGS = [
    'a', 'aside', 'b', 'blockquote', 'br', 'code', 'em', 'figcaption', 'figure',
    'h3', 'h4', 'hr', 'i', 'iframe', 'img', 'li', 'ol', 'p', 'pre', 's',
    'strong', 'u', 'ul', 'video'
]

因为我是初学者,试了很多才来这里问。

我尝试使用 Beautifulsoup get_text 方法,但它会修剪所有标签。 这让我很困扰,因为我还想保留一些,比如<img><a><b>,因为我希望仍然能够看到图像和链接。

我也尝试过 html.parser 和 python,但我不能直接入侵它。

我也试过一些在线服务,比如Mercury Spotlight Parser。 不错的服务,但它仍然保留了一些不需要的标签,例如 <div>。 我已经做了一些黑客来摆脱这些,但我认为这项服务是行不通的,因为它在解析德语变音字符时给了我 unicode "character not found" (u+FFFD),比如 Möglichkeit.

我理想的解决方案是一个函数,它将 ALLOWED_TAGS 作为白名单,然后修剪所有不在此列表中的 html 标签。

是否存在这样的库/函数?

我在 Ubuntu 上与 Python3 合作。

提前致谢。

此函数应该 return 所有唯一的 html 元素,如果它们(以及其中的元素)在 allowed_tags 列表中

def allowedTags(soup, allowed_tags):
    tags = []
    for tag in soup.find_all(allowed_tags) : 
        if all(t.name in allowed_tags for t in tag.find_all()) : 
            if tag not in tags and not any(str(tag) in str(t) for t in tags if t != tag) : 
                tags += [tag]
    return tags

请注意,大页面可能会非常慢(此页面需要 4.5 秒)
我尝试使用 tag.children 将时间减少到 0.5 秒,但我无法获得准确的结果