Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-从用户输入的数据中过滤链接_Python_Html - Fatal编程技术网

Python-从用户输入的数据中过滤链接

Python-从用户输入的数据中过滤链接,python,html,Python,Html,从用户输入的数据中筛选链接并创建锚定链接然后在html中使用的安全有效方法是什么。就像写问题时,复制粘贴链接,它会自动成为锚定链接。用于查找URI import re text = "foo http://www.stackoverflow.com bar" uri_re = re.compile(r"""(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|""" r"""www\d{0,3}[.]|[a-z0-9.\

从用户输入的数据中筛选链接并创建锚定链接然后在html中使用的安全有效方法是什么。就像写问题时,复制粘贴链接,它会自动成为锚定链接。

用于查找URI

import re

text = "foo http://www.stackoverflow.com bar"

uri_re = re.compile(r"""(?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|"""
                    r"""www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?"""
                    r""":[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))"""
                    r"""*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|"""
                    r"""[^\s`!()\[\]{};:'".,<>?«»“”‘’]))""")

print uri_re.sub(r"""<a href="\g<0>">\g<0></a>""", text)

在运行此脚本之前,是否应该对文本进行转义/清理?我会先清理,然后再修复链接。修复链接是什么意思?修复链接是指我在回答中发布的内容:添加HTML标记以将裸体URI转换为链接。
foo <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a> bar
text = "foo www.stackoverflow.com bar"

def link(match):
    uri = match.group()
    if ":" not in uri[:7]:
        uri = "http://" + uri
    return r"""<a href="{0}">{0}</a>""".format(uri)

print uri_re.sub(link, text)