zoukankan      html  css  js  c++  java
  • 使用python查询天气

    python主代码

    weather.py 


    import urllib2
    import json
    from city import city

    cityname = raw_input('你想查哪个城市的天气? ')
    citycode = city.get(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 %s ~ %s') % (
           result['weather'],
           result['temp2'],
           result['temp1']
           )
       print str_temp

     抓取city.py的数据代码 

    import urllib2

    url1 = 'http://m.weather.com.cn/data5/city.xml'
    content1 = urllib2.urlopen(url1).read()
    provinces = content1.split(',')
    result = 'city = { '
    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()
        cities = content2.split(',')
        for c in cities:
            c_code = c.split('|')[0]
            url3 = url % c_code
            content3 = urllib2.urlopen(url3).read()
            districts = content3.split(',')
            for d in districts:
                d_pair = d.split('|')
                d_code = d_pair[0]
                name = d_pair[1]
                url4 = url % d_code
                content4 = urllib2.urlopen(url4).read()
                code = content4.split('|')[1]
                line = "    '%s': '%s', " % (name, code)
                result += line
                print  name + ':' + code
    result += '}'
    f = file('/home/crossin/Desktop/city.py''w')
    f.write(result)
    f.close()

    city.py

    http://pan.baidu.com/share/link?shareid=1471212773&uk=204484850

  • 相关阅读:
    实验楼之Linux快捷、用户及文件权限、文件查看
    《生物信息学》——李霞;;生信概念
    MySQL 之 导出导入数据
    MySQL 之 扩展例子
    MySQL之创、增、删、改、查
    R 中数据导入
    神经网络,25个术语
    Python之文件输入输出,
    爬虫之BeautifulSoup, CSS
    Linux软连接和硬链接
  • 原文地址:https://www.cnblogs.com/jackyshan/p/3545459.html
Copyright © 2011-2022 走看看