Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

open persian url domains with urllib2

Tags:

python

url

utf-8

i'm trying to open an url http://الاعلي-للاتصالات.قطر/ar/news-events/event/future-internet-privacy with the urllib2.urlopen but it reports always an error.

The similar occurs to http://الاعلي-للاتصالات.قطر/ar ... other pages (chinese ones) are opened ok.

Any ideas to point me to the right way to open those urls?

urllib2.urlopen("http://الاعلي-للاتصالات.قطر/ar/news-events/event/future-internet-privacy").read()

urllib2.urlopen('http://الاعلي-للاتصالات.قطر').read()

[Edited] the error is :

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)

I also tried with the u'http://الاعلي-للاتصالات.قطر'.encode('utf-8') but the result url can't be opened too.

like image 506
Tony Avatar asked Feb 22 '23 09:02

Tony


1 Answers

As @Donal says, the URL has to be punycoded. Luckily Python includes this already. Here is a sample Python code

domain = "الاعلي-للاتصالات.قطر"
domain_unicode = unicode(domain, "utf8")
domain_idna = domain_unicode.encode("idna")
urllib2.urlopen("http://" + domain_idna).read()

Hope this helps.

like image 59
lunohodov Avatar answered Feb 24 '23 22:02

lunohodov