import urllib.request
import gzip
import json
print('------天气查询------')
def get_weather_data() :
city_name = input('请输入要查询的城市名称:')
url1 = 'http://wthrcdn.etouch.cn/weather_mini?city='+urllib.parse.quote(city_name)
url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
#网址1只需要输入城市名,网址2需要输入城市代码
#print(url1)
weather_data = urllib.request.urlopen(url1).read()
#读取网页数据
weather_data = gzip.decompress(weather_data).decode('utf-8')
#解压网页数据
weather_dict = json.loads(weather_data)
#将json数据转换为dict数据
return weather_dict def show_weather(weather_data):
weather_dict = weather_data
#将json数据转换为dict数据
if weather_dict.get('desc') == 'invilad-citykey':
print('你输入的城市名有误,或者天气中心未收录你所在城市')
elif weather_dict.get('desc') =='OK':
forecast = weather_dict.get('data').get('forecast')
print('城市:',weather_dict.get('data').get('city'))
print('温度:',weather_dict.get('data').get('wendu')+'℃ ')
print('感冒:',weather_dict.get('data').get('ganmao'))
print('风向:',forecast[0].get('fengxiang'))
print('风级:',forecast[0].get('fengli'))
print('高温:',forecast[0].get('high'))
print('低温:',forecast[0].get('low'))
print('天气:',forecast[0].get('type'))
print('日期:',forecast[0].get('date'))
print('*******************************')
four_day_forecast =input('是否要显示未来四天天气,是/否:')
if four_day_forecast == '是' or 'Y' or 'y':
for i in range(1,5):
print('日期:',forecast[i].get('date'))
print('风向:',forecast[i].get('fengxiang'))
print('风级:',forecast[i].get('fengli'))
print('高温:',forecast[i].get('high'))
print('低温:',forecast[i].get('low'))
print('天气:',forecast[i].get('type'))
print('--------------------------')
print('***********************************') show_weather(get_weather_data())

运行

------天气查询------
请输入要查询的城市名称:北京
城市: 北京
温度: 0℃
感冒: 昼夜温差较大,较易发生感冒,请适当增减衣服。体质较弱的朋友请注意防护。
风向: 西南风
风级: <![CDATA[<3级]]>
高温: 高温 2℃
低温: 低温 -6℃
天气: 多云
日期: 21日星期六
*******************************
是否要显示未来四天天气,是/否:是
日期: 22日星期天
风向: 无持续风向
风级: <![CDATA[<3级]]>
高温: 高温 5℃
低温: 低温 -5℃
天气: 多云
--------------------------
日期: 23日星期一
风向: 东北风
风级: <![CDATA[<3级]]>
高温: 高温 3℃
低温: 低温 -5℃
天气: 多云
--------------------------
日期: 24日星期二
风向: 南风
风级: <![CDATA[<3级]]>
高温: 高温 1℃
低温: 低温 -5℃
天气: 阴
--------------------------
日期: 25日星期三
风向: 北风
风级: <![CDATA[<3级]]>
高温: 高温 6℃
低温: 低温 -5℃
天气: 晴
--------------------------
***********************************

=================绘制曲线 gisoracle================

# -*- coding: utf-8 -*-

# 功能:查询城市天气
import requests, json, re
from matplotlib import pyplot as plt # 获取城市代码
def getCityCode(city):
url = 'http://toy1.weather.com.cn/search?cityname=' + city
r = requests.get(url)
if len(r.text) > 4:
json_arr = json.loads(r.text[1:len(r.text) - 1])
code = json_arr[0]['ref'][0:9]
return code
else:
return "" # 获取城市天气信息
def getWeatherInfo(city):
code = getCityCode(city)
url = 'http://t.weather.sojson.com/api/weather/city/' + code
r = requests.get(url)
info = r.json()
weather = {}
if info['status'] == 200:
weather['城市:'] = info['cityInfo']['parent'] + info['cityInfo']['city']
weather['时间:'] = info['time'] + ' ' + info['data']['forecast'][0]['week']
weather['温度:'] = info['data']['forecast'][0]['high'] + ' ' + info['data']['forecast'][0]['low']
weather['天气:'] = info['data']['forecast'][0]['type']
else:
weather['错误:'] = '[' + city + ']不存在!'
return weather # 打印天气信息
def printWeatherInfo(weather):
for key in weather:
print(key + weather[key]) # 获取未来气温
def getTemperatures(city):
code = getCityCode(city)
url = 'http://t.weather.sojson.com/api/weather/city/' + code
r = requests.get(url)
info = r.json()
temperatures = {}
if info['status'] == 200:
forecast = info['data']['forecast']
for i in range(len(forecast)):
dayinfo = forecast[i]
high = int(re.findall(r'\d+', dayinfo['high'])[0])
low = int(re.findall(r'\d+', dayinfo['low'])[0])
temperatures[dayinfo['ymd']] = [high, low]
else:
temperatures['错误:'] = '[' + city + ']不存在!'
return temperatures # 打印未来气温
def printTemperatures(temperatures):
if '错误:' not in temperatures.keys():
for key in temperatures:
print(key + ' 高温:' + str(temperatures[key][0]) + ' 低温:' + str(temperatures[key][1])) # 绘制未来气温折线图 def drawTemperatureLineChart():
temperatures = getTemperatures(city)
if '错误:' not in temperatures.keys():
dates = []
highs = []
lows = []
for key in temperatures:
dates.append(key)
highs.append(temperatures[key][0])
lows.append(temperatures[key][1])
fig = plt.figure(dpi=81, figsize=(5, 4))
plt.xlabel('Date (YYYY-MM-DD)', fontsize=10)
plt.ylabel("Temperature (℃)", fontsize=10)
fig.autofmt_xdate()
plt.plot(dates, highs, c='red', alpha=0.5)
plt.plot(dates, lows, c='blue', alpha=0.5)
plt.show() city = input('输入城市名:')
printWeatherInfo(getWeatherInfo(city))
printTemperatures(getTemperatures(city))
drawTemperatureLineChart()

python 获取天气信息,并绘制曲线的更多相关文章

  1. python 获取天气信息

    [说明]接口为聚合数据接口.API使用说明: 实现代码: import requests,json def main(): #参数 farmat=1 cityname = input("请输 ...

  2. 半吊子学习Swift--天气预报程序-获取天气信息

    昨天申请的彩云天气Api开发者今天上午已审核通过  饭后运动过后就马不停蹄的来测试接口,接口是采用经纬度的方式来获取天气信息,接口地址如下 https://api.caiyunapp.com/v2/ ...

  3. 内网公告牌获取天气信息解决方案(C# WebForm)

    需求:内网公告牌能够正确显示未来三天的天气信息 本文关键字:C#/WebForm/Web定时任务/Ajax跨域 规划: 1.天定时读取百度接口获取天气信息并存储至Txt文档: 2.示牌开启时请求Web ...

  4. C#调用WebService获取天气信息

    概述 本文使用C#开发Winform应用程序,通过调用<WebXml/>(URL:http://www.webxml.com.cn)的WebService服务WeatherWS来获取天气预 ...

  5. java获取天气信息

    通过天气信息接口获取天气信息,首先要给项目导入程序所需要的包,具体需要如下几个包: json-lib-2.4.jar ezmorph-1.0.6.jar commons-beanutils-1.8.3 ...

  6. Kettle通过Webservice获取天气信息

      Kettle通过Webservice获取天气信息 需求: 通过kettle工具,通过webservice获取天气信息,写成xml格式文件. 思路: Kettle可通过两种选择获取webservic ...

  7. Java通过webservice接口获取天气信息

    通过SOAP请求的方式获取天气信息并解析返回的XML文件. 参考: http://www.webxml.com.cn/WebServices/WeatherWS.asmx import java.io ...

  8. ajax无刷新获取天气信息

    浏览器由于安全方面的问题,禁止ajax跨域请求其他网站的数据,但是可以再本地的服务器上获取其他服务器的信息,在通过ajax请求本地服务来实现: <?php header("conten ...

  9. Android实现自动定位城市并获取天气信息

    定位实现代码: <span style="font-size:14px;">import java.io.IOException; import java.util.L ...

随机推荐

  1. 【转】Webpack 快速上手(中)

    由于文章篇幅较长,为了更好的阅读体验,本文分为上.中.下三篇: 上篇介绍了什么是 webpack,为什么需要 webpack,webpack 的文件输入和输出 中篇介绍了 webpack 在输入和输出 ...

  2. hibernate Criteria中多个or和and的用法 and ( or or)

    /s筛选去除无效数据 /*      detachedCriteria.add( Restrictions.or( Restrictions.like("chanpin", &qu ...

  3. 18、git提交代码并将develop分支合并到master分支上

    提交合并代码流程: git add .git commit -m ''git pushgit checkout mastergit merge develop //将develop 分支与master ...

  4. centos逻辑卷使用

    要求:  1.硬盘格式成物理卷pvpvcreate/dev/sdb/dev/sda 2.创建卷组vgcreatevg1000/dev/sdb1/dev/sdb2#创建卷组”vg1000” 3.增加卷组 ...

  5. 在 Vim 中,删除 ^@ 符号的几种方法

    在 Vim 中,^@ 表示 ASCII 码中的 NULL 字符,编码为 0x00,占用一个字节. 删除方法 方法1,采用 <CTRL-V><CTRL-J> 或 <CTRL ...

  6. Linux系统密码复杂度安全配置

    密码有效期控制 在文件/etc/login.defs中进行设置,如下参数 PASS_MAX_DAYS 180 #密码最长过期天数 PASS_MIN_DAYS 30 #密码最小过期天数 PASS_MIN ...

  7. Lnmp环境安装禅道项目管理软件

    1.本地环境 CentOS Linux release 7.5.1804 (Core) PHP 7.1.0-dev (cli) mysql Ver 14.14 Distrib 5.7.22 nginx ...

  8. 接触手机脚本编程------基于触动精灵的lua编程

    Auto.js好用多了,还不用root直接能用,我为什么学这个呢..... 最近因为学习需要开始接触一门新的脚本语言,我更深刻的发现了,语言只是一种工具,重要的是解决问题的思维,由于这次是需要我快速掌 ...

  9. 浅谈Flask 中的 线程局部变量 request 原理

    2017-11-27 17:25:11 晚橙 阅读数 600更多 分类专栏: Flask python 多线程   版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出 ...

  10. 理解cookie,session,token

    彻底理解cookie,session,token 发展史 1.很久很久以前,Web 基本上就是文档的浏览而已, 既然是浏览,作为服务器, 不需要记录谁在某一段时间里都浏览了什么文档,每次请求都是一个新 ...