3

我尝试访问带有重音符号的 URL,但它不起作用:

#!/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'

你有什么想法我的错误在哪里吗?

4

1 回答 1

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)
于 2013-03-28T09:11:02.190 回答