【04】天气查询应用(第四课)

在第三课我们抓取了city的代码放在了city.py中;

其实第三课的代码运行你会发现一个问题,抓取一段时间后发现程序就会出现异常。根本抓不下来城市的代码。这是因为脚本在短时间内频繁的抓取服务器上的信息会被误认为是攻击,导致服务器禁止了脚本的抓取。如果大家有解决办法,也告诉我一下,一起学习吗。等找到解决方案,我会写下来。

下面我们进行第四步吧。

在编写一个天气查询脚本我们的任务就完成了:

 1 #!/usr/bin/python   
 2 # -*- coding: gb2312 -*-
 3 import urllib2
 4 import json
 5 from city import city
 6 
 7 while True:
 8     cityname = raw_input('你想查那个城市的天气?\n')
 9     citycode = city[cityname]
10     if citycode:
11         url = ('http://www.weather.com.cn/data/cityinfo/%s.html' % citycode)
12         content = urllib2.urlopen(url).read()
13         data = json.loads(content)
14         result = data['weatherinfo']
15         str_temp = ('%s\n%s~%s') % (result['weather'],result['temp1'],result['temp2'])
16         print str_temp
17     else:
18         print '没有找到城市'
19         break

 

posted @ 2014-04-09 20:32  _level_  阅读(149)  评论(0编辑  收藏  举报