简体   繁体   English

漂白剂:如何将 nofollow 属性添加到现有链接?

[英]Bleach: How to add nofollow attribute to existing links?

I am aware that it is possible to linkify URLs that have not yet become html links, and Bleach will automatically add rel="nofollow" .我知道可以链接尚未成为 html 链接的 URL,并且 Bleach 会自动添加rel="nofollow" (Source: http://bleach.readthedocs.io/en/latest/linkify.html ) (来源: http : //bleach.readthedocs.io/en/latest/linkify.html

But how do I add the nofollow attribute to URLs that are already html links (ie they are already <a> tags)?但是如何将 nofollow 属性添加到已经是 html 链接的 URL(即它们已经是<a>标签)?

It's an old question, but since it still shows up in search results, I think it's worth answering anyway.这是一个老问题,但由于它仍然出现在搜索结果中,我认为无论如何都值得回答。

Bleach's linkify() does process both the pre-existing <a> links and link-like text.漂白剂的linkify()做处理预先存在的两个<a>链接和链接般的文字。 So all you need to add rel="nofollow" to all the links in the html fragment is to call linkify()所以你需要在 html 片段中的所有链接中添加rel="nofollow"就是调用linkify()

def add_nofollow(text_html):
    linker = bleach.linkifier.Linker()
    return linker.linkify(text_html)

Or, if only the pre-existing links need to be processed, a custom filter may be used to discard all new links:或者,如果需要处理预先存在的链接,则可以使用自定义过滤器来丢弃所有新链接:

def add_nofollow_nonew(text_html):

    def linker_callback(attrs, new=False):
        if new:
            return None
        return attrs

    linker = bleach.linkifier.Linker(callbacks = [linker_callback] + bleach.linkifier.DEFAULT_CALLBACKS)
    return linker.linkify(text_html)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM