python实现自主查询实时天气

yipeiwu_com6年前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的Flask框架中集成CKeditor富文本编辑器的教程

CKeditor是目前最优秀的可见即可得网页编辑器之一,它采用JavaScript编写。具备功能强大、配置容易、跨浏览器、支持多种编程语言、开源等特点。它非常流行,互联网上很容易找到相关...

Python计算回文数的方法

本文实例讲述了Python计算回文数的方法。分享给大家供大家参考。具体如下: 这里检查数字是不是回文数,用196算法生成一个数字的回文数 num = 905; def is_Pali...

Python 快速实现CLI 应用程序的脚手架

Python 快速实现CLI 应用程序的脚手架

今天跟大家分享一下如何快速实现一个Python CLI应用程序的脚手架,之所以会做这个是因为当时需要做一个运维的小工具希望用命令行的方式来使用,但是搜遍网上很多资料都没有系统讲解从开发、...

Python中返回字典键的值的values()方法使用

 values()方法返回给定的字典中所有可用值的列表。 语法 以下是values()方法的语法: dict.values() 参数   &...

python 并发编程 阻塞IO模型原理解析

python 并发编程 阻塞IO模型原理解析

阻塞IO(blocking IO) 在linux中,默认情况下所有的socket都是blocking,一个典型的读操作流程大概是这样: 当用户进程调用了recvfrom这个系统调用,k...