python - 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))
推荐阅读
- java - 正则表达式更改电话号码的形式
- javascript - 从另一个组件重新渲染组件的一部分
- c# - 困惑:抽象类属性
- google-chrome - 流行浏览器中的 Webcryto getRandomValues() 实现
- javascript - 当用户单击提交时,我的 AJAX 没有发布或响应
- android - 如何一键暂停/播放多个 MediaPlayer 对象?
- python - 如何在顺序蜘蛛之间传递数据
- r - ifelse 语句计算值是否大于其先前的值
- slack - Slack WebApi、Bot 用户与客户端凭据流?
- python - 当我将新项目添加到现有列表时,为什么所有元素都更改为新项目?