码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2016-09-10 16:02:04      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:

查询城市天气最后一节

需要导入上一节的结果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(‘没有找到该城市!‘)

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

标签:

原文地址:http://www.cnblogs.com/xiaoyingbianbianbian/p/5859432.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!