python实现自主查询实时天气

yipeiwu_com5年前Python基础

本文实例为大家分享了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\n" % (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('\n')[0] 
  name = line.split(':')[0] 
  code = line.split(':')[1] 
  city[name] = code 
cityname = raw_input('请输入你要查询的城市名称:\n') 
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\n%s ~ %s') % (result['weather'],result['temp1'],result['temp2']) 
    print str_temp 
  except: 
    print '查询失败' 
else: 
  print '没有找到该城市' 

运行 findweather  即可。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现登陆文件验证方法

Python实现登陆文件验证方法

代码主要功能: 利用Python实现简单的登陆验证,代码主要有两个部分组成: 第一部分:登陆页面,作用是实现用户名和密码的输入 利用两个输入函数input()来实现对用户名和密码的输入...

python使用wxpy轻松实现微信防撤回的方法

最近比较闲就随便瞎看,看到了微信防撤回就顺便跟着学着实现一下 使用的是wxpy,安装方法pip install wxpy(我使用的是python2.7),这样实现起来比较快,反正也只是练...

Python2.6版本中实现字典推导 PEP 274(Dict Comprehensions)

之前自己也遇到过一次,这段时间在群里也遇到过几次的一个问题 用python2.7写的一段程序,里面用到了字典推导式,但是服务器版本是python2.6,无法运行。 今天查了下关于Dict...

Tensorflow 实现分批量读取数据

之前的博客里使用tf读取数据都是每次fetch一条记录,实际上大部分时候需要fetch到一个batch的小批量数据,在tf中这一操作的明显变化就是tensor的rank发生了变化,我目前...

Python中.py文件打包成exe可执行文件详解

Python中.py文件打包成exe可执行文件详解

前言 最近做了几个简单的爬虫python程序,于是就想做个窗口看看效果。 首先是,窗口的话,以前没怎么接触过,就先考虑用Qt制作简单的ui。这里用前面sinanews的爬虫脚本为例,制作...