[英]Bleach: How to add nofollow attribute to existing links?
我知道可以鏈接尚未成為 html 鏈接的 URL,並且 Bleach 會自動添加rel="nofollow"
。 (來源: http : //bleach.readthedocs.io/en/latest/linkify.html )
但是如何將 nofollow 屬性添加到已經是 html 鏈接的 URL(即它們已經是<a>
標簽)?
這是一個老問題,但由於它仍然出現在搜索結果中,我認為無論如何都值得回答。
漂白劑的linkify()
做處理預先存在的兩個<a>
鏈接和鏈接般的文字。 所以你需要在 html 片段中的所有鏈接中添加rel="nofollow"
就是調用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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.