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)