Bleach: How to add nofollow attribute to existing links?

272 Views Asked by At

I am aware that it is possible to linkify URLs that have not yet become html links, and Bleach will automatically add rel="nofollow". (Source: http://bleach.readthedocs.io/en/latest/linkify.html)

But how do I add the nofollow attribute to URLs that are already html links (i.e. they are already <a> tags)?

1

There are 1 best solutions below

0
On

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. So all you need to add rel="nofollow" to all the links in the html fragment is to call 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)