Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 with urllib and accent

I try to access an URL with an accent but it didn't work:

#!/usr/bin/python3.3
# -*- coding: utf-8 -*- 

import urllib.request

response = urllib.request.urlopen("http://nominatim.openstreetmap.org/search.php?city=Lévis&format=json")
content = response.read()
print(content)

When I execute this code I have this error in return

UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 22: ordinal not in range(128)

So I try this

response = urllib.request.urlopen("http://nominatim.openstreetmap.org/search.php?city=Lévis&format=json".encode("UTF-8"))

But still an error

AttributeError: 'bytes' object has no attribute 'timeout'

Do you have any ideas where is my mistake ?

like image 661
Jean Avatar asked Oct 28 '25 12:10

Jean


1 Answers

You need to escape your query parameters, like @Cairnarvon said:

import urllib.parse

city = 'Lévis'
query = "city=%s&format=json" % (urllib.parse.quote(city),)
response = urllib.request.urlopen("http://nominatim.openstreetmap.org/search.php?" + query)
like image 173
Fredrik Håård Avatar answered Oct 31 '25 02:10

Fredrik Håård



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!