示例代码:
#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)