如何解决Python - 开放天气地图编码 åäö
当从 openweathermap 请求 json 时,我遇到了字母 åäö (\xe4 \xe5 \xe6) 的一些问题。我该怎么做才能以正确的方式对其进行编码?
UnicodeEncodeError: 'ascii' codec can't encode character '\xe5' in position 27: ordinal not in range(128)
import json
from urllib.request import urlopen
def getSource(city,countrycode):
url = "http://api.openweathermap.org/data/2.5/weather?q={city},{countrycode}&appid=xxx".format(city=city,countrycode=countrycode)
with urlopen(url) as response:
source = response.read()
return(source)
source = getSource("Borås","se")
data = json.loads(source)
print(json.dumps(data,indent=2))
解决方法
我没有 API id,但是你能不能试试 urllib 中的 parse.quote,像这样:
import json
from urllib.request import urlopen
from urllib.parse import quote
def getSource(city,countrycode):
url = "http://api.openweathermap.org/data/2.5/weather?q="+quote(city)+"{countrycode}&appid=xxx".format(city=city,countrycode=countrycode)
with urlopen(url) as response:
source = response.read()
return(source)
source = getSource("Borås","se")
data = json.loads(source)
print(json.dumps(data,indent=2))
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。