• python 实现自主查询实时天气


    用到了urllib2 json  很简单的一个应用 如下 

          

    获取城市编号

    #coding=utf-8
    import urllib2
    
    url1 = 'http://m.weather.com.cn/data3/city.xml'
    content1 = urllib2.urlopen(url1).read()
    provinces = content1.split(',')
    print content1 # 输出content1可以查看全部省份代码
    result = ''
    url = 'http://m.weather.com.cn/data3/city%s.xml'
    for p in provinces:
        p_code = p.split('|')[0]
        url2 = url % p_code
        content2 = urllib2.urlopen(url2).read() # 输出content2可以查看此省份下所有城市代码
        cities = content2.split(',')
        print content2
        for c in cities:
            c_code = c.split('|')[0]
            url3 = url % c_code
            content3 = urllib2.urlopen(url3).read()
            print content3  #content3是此城市下所有地区代码
            districts = content3.split(',')
            for d in districts: # 对于每个地区,我们把它的名字记录下来,然后再发送一次请求,得到它的最终代码:
                d_pair = d.split('|')
                d_code = d_pair[0] #
                if 5 == len(d_code):
                    continue
                    temp=[d_code]
                    temp.insert(4,0)
                    d_code ="".join(temp)
                name = d_pair[1] # 名字
                url4 = url % d_code
                content4 = urllib2.urlopen(url4).read()
                print content4
                code = content4.split('|')[1]
                line = "%s:%s
    " % (name, code)
                result += line
                print name + ':' + code
    f = file('./city', 'w')
    f.write(result)
    f.close()

    findweather

    # -*- coding: utf-8 -*-
    import urllib2
    import json
    city = {}
    f =file('city','r')
    src = f.readlines()
    for line in src:
        line = line.split('
    ')[0]
        name = line.split(':')[0]
        code = line.split(':')[1]
        city[name] = code
    cityname = raw_input('请输入你要查询的城市名称:
    ')
    citycode = city.get(cityname)
    print cityname
    if citycode:
        try:
            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
    %s ~ %s') % (result['weather'],result['temp1'],result['temp2'])
            print str_temp
        except:
            print '查询失败'
    else:
        print '没有找到该城市'

    运行 findweather 即可
     

    关注公众号 海量干货等你
  • 相关阅读:
    js的实例方法和静态方法分析
    简述TCP连接的建立与释放(三次握手、四次挥手)
    CSS中各种各样居中方法的总结
    队列的JS实现
    栈的JS实现
    单链表、循环链表的JS实现
    双向链表、双向循环链表的JS实现
    简述JavaScript对象、数组对象与类数组对象
    简述HTML DOM及其节点分类
    关于DOM对象与JQuery对象的那些事
  • 原文地址:https://www.cnblogs.com/sowhat1412/p/12734390.html
Copyright © 2020-2023  润新知