我知道链接那些还没有变成html链接的URL是可能的,Bleach会自动添加rel="nofollow"。(来源:http://bleach.readthedocs.io/en/latest/linkify.html)
但是,如何将nofollow属性添加到已经是html链接的URL(即,它们已经是<a>标记)?
发布于 2020-11-15 23:26:49
这是一个古老的问题,但由于它仍然出现在搜索结果中,我认为无论如何它都值得回答。
Bleach的linkify()可以同时处理预先存在的<a>链接和类似链接的文本。因此,要将rel="nofollow"添加到html片段中的所有链接,只需调用linkify()
def add_nofollow(text_html):
linker = bleach.linkifier.Linker()
return linker.linkify(text_html)或者,如果仅需要处理的预先存在的链接,则可以使用自定义过滤器来丢弃所有新链接:
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)https://stackoverflow.com/questions/42943411
复制相似问题