我正在尝试使用 rel="nofollow"参数关闭所有外部 url:
我写了这个简单的中间件:
import re
NOFOLLOW_RE = re.compile(u'<a (?![^>]*rel=["\']nofollow[\'"])'\
u'(?![^>]*href=["\']mysite\.com[\'"])',
re.UNICODE|re.IGNORECASE)
class NofollowLinkMiddleware(object):
def process_response(self, request, response):
if ("text" in response['Content-Type']):
response.content = re.sub(NOFOLLOW_RE, u'<a rel="nofollow" ', response.content.decode('UTF8') )
return response
else:
return response
它有效,但会关闭所有内部和外部链接。而且我不知道如何添加
最佳答案
起初,您忘记了“http://”和 url 路径。所以,你的正则表达式应该是:
NOFOLLOW_RE = re.compile(u'<a (?![^>]*rel=["\']nofollow[\'"])'\
u'(?![^>]*href=["\']http://mysite\.com(/[^\'"]*)?[\'"])',
re.U|re.I)
然后,你还需要考虑以“/”和“#”开头的hrefs作为内部链接:
NOFOLLOW_RE = re.compile(u'<a (?![^>]*rel=["\']nofollow[\'"])'\
u'(?![^>]*href=["\'](?:https?://mysite\.com(?:/[^\'"]*)|/[^\'"]*|#[^\'"]*)[\'"])',
re.U|re.I)
此外,您可能希望考虑第 3 级域和“https://”协议(protocol)。
对于
NOFOLLOW_RE = re.compile(u'<a (?P<link>(?![^>]*rel=["\']nofollow[\'"])'\
u'(?![^>]*href=["\'](?:https?://mysite\.com(?:/[^\'"]*)|/[^\'"]*|#[^\'"]*)[\'"]).*?</a>)',
re.U|re.I)
...
response.content = NOFOLLOW_RE.sub(u'<noindex><a rel="nofollow" \g<link></noindex>', your_html)
这个正则表达式很古怪。我强烈建议您为它编写一个测试,使用 标签的所有可能组合以及您可以想象的属性。如果您之后在这段代码中发现了一些问题,测试将帮助您不要破坏所有内容。
关于python - 用于为所有外部链接添加 relnofollow 的 Django 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11562701/