Python 学习之urllib模块---用于发送网络请求,获取数据(5)

时间:2022-11-01 15:45:36

查询城市天气最后一节

需要导入上一节的结果city10.py

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import urllib.request
from  city10 import city     #从city10.py里导入city变量名称
import json         #json包,loads的用法
import traceback

cityname=input('你想查询什么城市的天气?\n')

citycode=city.get(cityname) # citycode=city[cityname]
#print (citycode)

#print (cityname)

if citycode:
    try:
        web='http://www.weather.com.cn/data/cityinfo/%s.html' %citycode
        content=urllib.request.urlopen(web).read().decode()
        data=json.loads(content)
        #print (data)
        print(type(content))
        print(type(data))

result=data['weatherinfo'] #获取weatherinfo键的值为{'cityid':'101010100'}
        # 就好比result={}
        a=('%s\n%s~%s')%(result['weather'], result['temp1'], result['temp2'])
        print(a)
    except Exception as e:
        #traceback.print_exc()
        print(Exception,":",e)
        print('查询失败')
else:
    print('没有找到该城市!')