我尝试访问带有重音的网址但不起作用:
#!/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)
当我执行此代码时,我会收到此错误
UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 22: ordinal not in range(128)
所以我试试这个
response = urllib.request.urlopen("http://nominatim.openstreetmap.org/search.php?city=Lévis&format=json".encode("UTF-8"))
但仍然是错误
AttributeError: 'bytes' object has no attribute 'timeout'
你有什么想法我错了吗?
答案 0 :(得分:5)
你需要转义你的查询参数,比如@Cairnarvon说:
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)