python网页爬虫之天气查询

这是用python写的天气查询代码,可用。
这里用的是和风天气的接口
参考:http://www.heweather.com/documents/dev-sample#python
我用的城市数据:http://download.csdn.net/detail/yabaj/9432163
将城市数据存放本地:

jsons = {这里是城市数据}
import pickle
pickle_file = open('city_data.pkl', 'wb')
pickle.dump(jsons, pickle_file)
pickle_file.close()
import urllib.request
import json
import pickle
from datetime import date

city1 = []
city2 = []
num = ''#城市编码

def loadData():
    pickle_file = open('city_data.pkl', 'rb')
    global city1
    city1 = pickle.load(pickle_file)

def init():
    loadData()
    while 1:
        flag = 0
        p = input('请输入省:')
        for each in city1:
            if each['省'] == p:
                flag = 1
                global city2
                city2 = each['市']
                break

        if flag == 0:
            print ('输入的省不存在!')
            continue
        else:
            while 1:
                c = input('请输入城市:')
                for each in city2:
                    if each['市名'] == c:
                        flag = 0
                        global num
                        num = each['编码']
                        break
                if flag == 1:
                    print ('输入的城市不存在!')
                    continue
                else:
                    return

while 1:
    init()   
    url = 'https://api.heweather.com/x3/weather?cityid=CN' + num + '&key=自己的key值'
    data = None
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}  
    req = urllib.request.Request(url, data, headers=headers)
    weatherHTML = urllib.request.urlopen(req).read().decode('utf-8')# 读入打开的url
    fn = str(date.today())+'.txt'
    #查询得到的数据存放本地
    weather_file = open(fn, 'w')
    weather_file.write(weatherHTML)
    weather_file.close()

    #print (weatherHTML)    
    weatherJSON = json.loads(weatherHTML)# 创建json
    weatherInfo = weatherJSON["HeWeather data service 3.0"]
    # 打印信息

    print ('城市:', weatherInfo[0]['basic']['city'])
    print ('更新时间:', weatherInfo[0]['basic']['update']['loc'])
    print ('24小时天气:')
    print ('温度:', weatherInfo[0]['daily_forecast'][0]['tmp']['max'], '-', weatherInfo[0]['daily_forecast'][0]['tmp']['min'])
    print ('天气:', weatherInfo[0]['daily_forecast'][0]['cond']['txt_d'], ',', weatherInfo[0]['daily_forecast'][0]['cond']['txt_n'])
    temp = input ('按任意键继续:')
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值