【问题标题】:Python - open weather map encode åäöPython - 打开天气图编码åäö
【发布时间】:2021-06-07 12:12:02
【问题描述】:

当我从 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))

【问题讨论】:

  • UnicodeEncodeError 是否出现在 json.loads xor json.dumps 期间?
  • 是的。打印(json.dumps(数据,缩进=2))

标签: python openweathermap


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多