我正在尝试打开网址http://الاعلي-للاتصالات.قطر/ ar / news-events / event / future-internet-privacy 使用urllib2.urlopen但它总是报告错误。
类似的情况发生在http://الاعلي-للاتصالات.قطر/ ar ...其他页面(中文页面)打开确定。
有什么想法指出我打开这些网址的正确方法吗?
urllib2.urlopen("http://الاعلي-للاتصالات.قطر/ar/news-events/event/future-internet-privacy").read()
urllib2.urlopen('http://الاعلي-للاتصالات.قطر').read()
将帖子 错误是:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/urllib2.py", line 126, in urlopen
return _opener.open(url, data, timeout)
File "/usr/lib/python2.6/urllib2.py", line 391, in open
response = self._open(req, data)
File "/usr/lib/python2.6/urllib2.py", line 409, in _open
'_open', req)
File "/usr/lib/python2.6/urllib2.py", line 369, in _call_chain
result = func(*args)
File "/usr/lib/python2.6/urllib2.py", line 1170, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/usr/lib/python2.6/urllib2.py", line 1142, in do_open
h.request(req.get_method(), req.get_selector(), req.data, headers)
File "/usr/lib/python2.6/httplib.py", line 914, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python2.6/httplib.py", line 951, in _send_request
self.endheaders()
File "/usr/lib/python2.6/httplib.py", line 908, in endheaders
self._send_output()
File "/usr/lib/python2.6/httplib.py", line 780, in _send_output
self.send(msg)
File "/usr/lib/python2.6/httplib.py", line 759, in send
self.sock.sendall(str)
我也尝试过使用u'http://الاعلي-للاتصالات.قطر'.coding('utf-8'),但结果网址也无法打开。
答案 0 :(得分:8)
正如@Donal所说,网址必须是punycoded。幸运的是Python已经包含了这个。这是一个示例Python代码
domain = "الاعلي-للاتصالات.قطر"
domain_unicode = unicode(domain, "utf8")
domain_idna = domain_unicode.encode("idna")
urllib2.urlopen("http://" + domain_idna).read()
希望这有帮助。