【再回首Python之美】【url/json小酌】查天气(使用urllib2,json模块)

示例代码:

#ex_url.py
# -*- coding: utf-8 -*-

self_file = __file__    #save current file absolute address

import urllib2
import json

print "\nQuery BeiJing weather by urllib2"
url = "http://www.weather.com.cn/data/cityinfo/101010100.html"#BeiJing weather query result url
content_str = urllib2.urlopen(url).read()
print type(content_str)     #<type 'str'>
print content_str
#{
#"weatherinfo":{
#"city":"北京",
#"cityid":"101010100",
#"temp1":"-2℃",
#"temp2":"16℃",
#"weather":"晴",
#"img1":"n0.gif",
#"img2":"d0.gif",
#"ptime":"18:00"
#}
#}

print "\n Get data by json type"
data = json.loads(content_str)
print type(data)   #<type 'dict'>
print data
#{
#u'weatherinfo': {
#u'city': u'\u5317\u4eac',
#u'ptime': u'18:00',
#u'cityid': u'101010100',
#u'temp2': u'16\u2103',
#u'temp1': u'-2\u2103',
#u'weather': u'\u6674',
#u'img2': u'd0.gif',
#u'img1': u'n0.gif'
#}
#}

print "\n Get weather dict from data dict"
result_dict = data['weatherinfo']
print type(result_dict) #<type 'dict'>
print result_dict

print "\n dump weater"
print '%s    %s~%s' % (result_dict['city'], result_dict['temp1'], result_dict['temp2'])



print "\n exit %s" % self_file

编译执行:


(end)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值