Pythonで日本語を含む国際化ドメイン(IDNA)をPunycode変換する

Pythonで日本語を含む国際化ドメイン(IDNA)をPunycode変換する

utf-8でurlを渡して、Punycodeに変換する関数

import urllib
from urlparse import urlparse

def url_idna_quote(url):
	protocol, domain, path, params, query, fragment = urlparse(url)
	domain = unicode(domain, 'utf-8', 'ignore')
	domain = domain.encode('idna')
	if path is None:
		path = ''
	else:
		path = urllib.quote_plus(path, safe='=&?/')
	url = protocol + '://' + domain + path
	return url

実行結果

>>> url_idna_quote( 'http://日本語ドメイン.biz/aaaa/テスト/' )
'http://xn--eckwd4c7c5976acvb2w6i.biz/aaaa/%E3%83%86%E3%82%B9%E3%83%88/'
>>> url_idna_quote( 'http://Домен.com' )
'http://xn--d1acufc.com'