您的位置:首页 > 其它

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

2014-04-09 20:32 363 查看
在第三课我们抓取了city的代码放在了city.py中;

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

下面我们进行第四步吧。

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

#!/usr/bin/python
# -*- coding: gb2312 -*-
import urllib2
import json
from city import city

while True:
cityname = raw_input('你想查那个城市的天气?\n')
citycode = city[cityname]
if citycode:
url = ('http://www.weather.com.cn/data/cityinfo/%s.html' % citycode)
content = urllib2.urlopen(url).read()
data = json.loads(content)
result = data['weatherinfo']
str_temp = ('%s\n%s~%s') % (result['weather'],result['temp1'],result['temp2'])
print str_temp
else:
print '没有找到城市'
break
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: