python 利用json获取5天的天气

 时间:2024-10-24 22:12:21

1、首先是找到带有json文件的网址。网址:http://wthrcdn.etouch.cn/weather_mini?city=北京注意:这个网址的后面的地名可以自己更改,如http://wthrcdn.etouch.cn/weather_mini?city=上海对了,如果打开的页面是乱码,那是因为问个的显示编码方式不对,在网页单击鼠标右键,选择编码 ,选择Unicode(UTF-8),用的浏览器不一样,操作方式应该不一样,只要将网站的显示页面的编码方式改成utf-8就行了

python 利用json获取5天的天气

6、接下来就是对这个字典(weatherData)的数据进行处理就是平时处理字典与列表的方式即可。举例:获取今天的天气:weatherData['data']['forecast'][0]['type']#输出>>'晴'获取今天的温度weatherData['data']['wendu'] #输出>>'16'

7、下面是获取天气的整个过程,我将源代码一起贴上:#!python3#coding:utf-8importjson,sys,r髫潋啜缅equests#输入地点weatherPlace=input("请输入天气地点:")ifweatherPlace=='E'orweatherPlace=='e':sys.exit(0);#关闭程序#下载天气JSONweatherJsonUrl="http://wthrcdn.etouch.cn/weather_mini?city=%s"%(weatherPlace)response=requests.get(weatherJsonUrl)try:response.raise_for_status()except:print("网址请求出错")#将json文件格式导入成python的格式weatherData=json.loads(response.text)#以好看的形式打印字典与列表表格#importpprint#pprint.pprint(weatherData)w=weatherData['data']print("地点:%s"%w['city'])#日期date_a=[]#最高温与最低温highTemp=[]lowTemp=[]#天气weather=[]#进行五天的天气遍历foriinrange(len(w['forecast'])):date_a.append(w['forecast'][i]['date'])highTemp.append(w['forecast'][i]['high'])lowTemp.append(w['forecast'][i]['low'])weather.append(w['forecast'][i]['type'])#输出print("日期:"+date_a[i])print("\t温度:最"+lowTemp[i]+'℃~最'+highTemp[i]+'℃')print("\t天气:"+weather[i])print("")print("\n今日着装:"+w['ganmao'])print("当前温度:"+w['wendu']+"℃") 上述代码在运行的时候要输入>> 地名<< ,如下图:

python 利用json获取5天的天气
  • 电脑学习通考试切换网页会被检测吗
  • python end用法
  • python 字符串strip方法的使用
  • Python中如何写注释
  • 热门搜索
    软件开发都学什么 引经据典是什么意思 盈余公积是什么意思 紫蓬山有什么好玩的 什么是信息技术? 质朴无华的意思 cps是什么意思 小孩生日祝福语大全 233333是什么意思 什么游戏好玩单机