首页 > 解决方案 > 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))

标签: pythonopenweathermap

解决方案


我没有 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))

推荐阅读