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  即可。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Python爬虫实例扒取2345天气预报

    寒假里学习了一下Python爬虫,使用最简单的方法扒取需要的天气数据,对,没听错,最简单的方法.甚至没有一个函数封装.. 网址:http://tianqi.2345.com/wea_history/53892.htm 火狐中右键查看网页源代码,没有发现天气数据,因此推断网页采用的json格式数据. 右击->查看元素->网络->JS,找到了位置 用Python爬虫下载为json格式数据存储下来,代码如下: #-*- coding:utf-8 -*- import urllib2 impor

  • Python实现从百度API获取天气的方法

    本文实例讲述了Python实现从百度API获取天气的方法.分享给大家供大家参考.具体实现方法如下: 复制代码 代码如下: __author__ = 'saint' import os import urllib.request import urllib.parse import json class weather(object):     # 获取城市代码的uri     code_uri = "http://apistore.baidu.com/microservice/cityinfo?

  • python3爬取各类天气信息

    本来是想从网上找找有没有现成的爬取空气质量状况和天气情况的爬虫程序,结果找了一会儿感觉还是自己写一个吧. 主要是爬取北京包括北京周边省会城市的空气质量数据和天气数据. 过程中出现了一个错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa1 in position 250. 原来发现是页面的编码是gbk,把语句改成data=urllib.request.urlopen(url).read().decode("gbk")就可以

  • python显示天气预报

    复制代码 代码如下: import urllib2import jsonimport stringurl ='http://m.weather.com.cn/data/101090502.html're = urllib2.urlopen(url).read()we = json.loads(re)['weatherinfo']print we['city'] , we['date_y'].center(30) ,   we['week']print we['temp1'], we['weath

  • python定时利用QQ邮件发送天气预报的实例

    大致介绍 好久没有写博客了,正好今天有时间把前几天写的利用python定时发送QQ邮件记录一下 1.首先利用request库去请求数据,天气预报使用的是和风天气的API(www.heweather.com/douments/api/s6/weather-forecast) 2.利用python的jinja2模块写一个html模板,用于展示数据 3.python的email构建邮件,smtplib发送邮件 4.最后使用crontab定时执行python脚本 涉及的具体知识可以去看文档,本文主要就是

  • python结合API实现即时天气信息

    python结合API实现即时天气信息 import urllib.request import urllib.parse import json """ 利用"最美天气"抓取即时天气情况 http://www.zuimeitianqi.com/ """ class ZuiMei(): def __init__(self): self.url = 'http://www.zuimeitianqi.com/zuimei/quer

  • Python天气预报采集器实现代码(网页爬虫)

    爬虫简单说来包括两个步骤:获得网页文本.过滤得到数据. 1.获得html文本. python在获取html方面十分方便,寥寥数行代码就可以实现我们需要的功能. 复制代码 代码如下: def getHtml(url): page = urllib.urlopen(url) html = page.read() page.close() return html 这么几行代码相信不用注释都能大概知道它的意思. 2.根据正则表达式等获得需要的内容. 使用正则表达式时需要仔细观察该网页信息的结构,并写出正

  • python解析中国天气网的天气数据

    使用方法:terminal中输入 复制代码 代码如下: python weather.py http://www.weather.com.cn/weather/101010100.shtml 北京6天的天气数据 json格式 复制代码 代码如下: #coding=utf-8  #weather.py  import urllib  import re  import simplejson  import sys if len(sys.argv) != 2:      print 'please

  • Python爬取国外天气预报网站的方法

    本文实例讲述了Python爬取国外天气预报网站的方法.分享给大家供大家参考.具体如下: crawl_weather.py如下: #encoding=utf-8 import httplib import urllib2 import time from threading import Thread import threading from Queue import Queue from time import sleep import re import copy lang = "fr&qu

  • Python爬虫天气预报实例详解(小白入门)

    本文研究的主要是Python爬虫天气预报的相关内容,具体介绍如下. 这次要爬的站点是这个:http://www.weather.com.cn/forecast/ 要求是把你所在城市过去一年的历史数据爬出来. 分析网站 首先来到目标数据的网页 http://www.weather.com.cn/weather40d/101280701.shtml 我们可以看到,我们需要的天气数据都是放在图表上的,在切换月份的时候,发现只有部分页面刷新了,就是天气数据的那块,而URL没有变化. 这是因为网页前端使用

随机推荐