我想知道什么是最好的方法 - 或者如果标准库有一个简单的方法 - 将域名和路径中的Unicode字符转换为等效的ASCII URL,使用域编码为IDNA和路径% -encoded,根据RFC 3986.
我从用户那里得到一个UTF-8的URL.因此,如果他们输入http://?.ws/?我'http://\xe2\x9e\xa1.ws/\xe2\x99\xa5'的Python.我想要的是ASCII版本:'http://xn--hgi.ws/%E2%99%A5'.
我现在所做的是通过正则表达式将URL拆分为多个部分,然后手动对域进行IDNA编码,并使用不同的urllib.quote()调用单独编码路径和查询字符串.
# url is UTF-8 here, eg: url = u'http://?.ws/?'.encode('utf-8')
match = re.match(r'([a-z]{3,5})://(.+\.[a-z0-9]{1,6})'
r'(:\d{1,5})?(/.*?)(\?.*)?$', url, flags=re.I)
if not match:
raise BadURLException(url)
protocol, domain, port, path, query = match.groups()
try:
domain = unicode(domain, 'utf-8')
except UnicodeDecodeError:
return '' # bad UTF-8 chars in domain
domain = domain.encode('idna')
if port is None:
port = ''
path = urllib.quote(path)
if query is None:
query = '' …Run Code Online (Sandbox Code Playgroud)