1. import urllib.request
  2. import gzip
  3. import json
  4. print('------天气查询------')
  5. def get_weather_data() :
  6. city_name = input('请输入要查询的城市名称:')
  7. url1 = 'http://wthrcdn.etouch.cn/weather_mini?city='+urllib.parse.quote(city_name)
  8. url2 = 'http://wthrcdn.etouch.cn/weather_mini?citykey=101010100'
  9. #网址1只需要输入城市名,网址2需要输入城市代码
  10. #print(url1)
  11. weather_data = urllib.request.urlopen(url1).read()
  12. #读取网页数据
  13. weather_data = gzip.decompress(weather_data).decode('utf-8')
  14. #解压网页数据
  15. weather_dict = json.loads(weather_data)
  16. #将json数据转换为dict数据
  17. return weather_dict
  18.  
  19. def show_weather(weather_data):
  20. weather_dict = weather_data
  21. #将json数据转换为dict数据
  22. if weather_dict.get('desc') == 'invilad-citykey':
  23. print('你输入的城市名有误,或者天气中心未收录你所在城市')
  24. elif weather_dict.get('desc') =='OK':
  25. forecast = weather_dict.get('data').get('forecast')
  26. print('城市:',weather_dict.get('data').get('city'))
  27. print('温度:',weather_dict.get('data').get('wendu')+'℃ ')
  28. print('感冒:',weather_dict.get('data').get('ganmao'))
  29. print('风向:',forecast[0].get('fengxiang'))
  30. print('风级:',forecast[0].get('fengli'))
  31. print('高温:',forecast[0].get('high'))
  32. print('低温:',forecast[0].get('low'))
  33. print('天气:',forecast[0].get('type'))
  34. print('日期:',forecast[0].get('date'))
  35. print('*******************************')
  36. four_day_forecast =input('是否要显示未来四天天气,是/否:')
  37. if four_day_forecast == '是' or 'Y' or 'y':
  38. for i in range(1,5):
  39. print('日期:',forecast[i].get('date'))
  40. print('风向:',forecast[i].get('fengxiang'))
  41. print('风级:',forecast[i].get('fengli'))
  42. print('高温:',forecast[i].get('high'))
  43. print('低温:',forecast[i].get('low'))
  44. print('天气:',forecast[i].get('type'))
  45. print('--------------------------')
  46. print('***********************************')
  47.  
  48. show_weather(get_weather_data())

运行

  1. ------天气查询------
  2. 请输入要查询的城市名称:北京
  3. 城市: 北京
  4. 温度: 0
  5. 感冒: 昼夜温差较大,较易发生感冒,请适当增减衣服。体质较弱的朋友请注意防护。
  6. 风向: 西南风
  7. 风级: <![CDATA[<3级]]>
  8. 高温: 高温 2
  9. 低温: 低温 -6
  10. 天气: 多云
  11. 日期: 21日星期六
  12. *******************************
  13. 是否要显示未来四天天气,是/否:是
  14. 日期: 22日星期天
  15. 风向: 无持续风向
  16. 风级: <![CDATA[<3级]]>
  17. 高温: 高温 5
  18. 低温: 低温 -5
  19. 天气: 多云
  20. --------------------------
  21. 日期: 23日星期一
  22. 风向: 东北风
  23. 风级: <![CDATA[<3级]]>
  24. 高温: 高温 3
  25. 低温: 低温 -5
  26. 天气: 多云
  27. --------------------------
  28. 日期: 24日星期二
  29. 风向: 南风
  30. 风级: <![CDATA[<3级]]>
  31. 高温: 高温 1
  32. 低温: 低温 -5
  33. 天气:
  34. --------------------------
  35. 日期: 25日星期三
  36. 风向: 北风
  37. 风级: <![CDATA[<3级]]>
  38. 高温: 高温 6
  39. 低温: 低温 -5
  40. 天气:
  41. --------------------------
  42. ***********************************

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

  1. # -*- coding: utf-8 -*-
  2.  
  3. # 功能:查询城市天气
  4. import requests, json, re
  5. from matplotlib import pyplot as plt
  6.  
  7. # 获取城市代码
  8. def getCityCode(city):
  9. url = 'http://toy1.weather.com.cn/search?cityname=' + city
  10. r = requests.get(url)
  11. if len(r.text) > 4:
  12. json_arr = json.loads(r.text[1:len(r.text) - 1])
  13. code = json_arr[0]['ref'][0:9]
  14. return code
  15. else:
  16. return ""
  17.  
  18. # 获取城市天气信息
  19. def getWeatherInfo(city):
  20. code = getCityCode(city)
  21. url = 'http://t.weather.sojson.com/api/weather/city/' + code
  22. r = requests.get(url)
  23. info = r.json()
  24. weather = {}
  25. if info['status'] == 200:
  26. weather['城市:'] = info['cityInfo']['parent'] + info['cityInfo']['city']
  27. weather['时间:'] = info['time'] + ' ' + info['data']['forecast'][0]['week']
  28. weather['温度:'] = info['data']['forecast'][0]['high'] + ' ' + info['data']['forecast'][0]['low']
  29. weather['天气:'] = info['data']['forecast'][0]['type']
  30. else:
  31. weather['错误:'] = '[' + city + ']不存在!'
  32. return weather
  33.  
  34. # 打印天气信息
  35. def printWeatherInfo(weather):
  36. for key in weather:
  37. print(key + weather[key])
  38.  
  39. # 获取未来气温
  40. def getTemperatures(city):
  41. code = getCityCode(city)
  42. url = 'http://t.weather.sojson.com/api/weather/city/' + code
  43. r = requests.get(url)
  44. info = r.json()
  45. temperatures = {}
  46. if info['status'] == 200:
  47. forecast = info['data']['forecast']
  48. for i in range(len(forecast)):
  49. dayinfo = forecast[i]
  50. high = int(re.findall(r'\d+', dayinfo['high'])[0])
  51. low = int(re.findall(r'\d+', dayinfo['low'])[0])
  52. temperatures[dayinfo['ymd']] = [high, low]
  53. else:
  54. temperatures['错误:'] = '[' + city + ']不存在!'
  55. return temperatures
  56.  
  57. # 打印未来气温
  58. def printTemperatures(temperatures):
  59. if '错误:' not in temperatures.keys():
  60. for key in temperatures:
  61. print(key + ' 高温:' + str(temperatures[key][0]) + ' 低温:' + str(temperatures[key][1]))
  62.  
  63. # 绘制未来气温折线图
  64.  
  65. def drawTemperatureLineChart():
  66. temperatures = getTemperatures(city)
  67. if '错误:' not in temperatures.keys():
  68. dates = []
  69. highs = []
  70. lows = []
  71. for key in temperatures:
  72. dates.append(key)
  73. highs.append(temperatures[key][0])
  74. lows.append(temperatures[key][1])
  75. fig = plt.figure(dpi=81, figsize=(5, 4))
  76. plt.xlabel('Date (YYYY-MM-DD)', fontsize=10)
  77. plt.ylabel("Temperature (℃)", fontsize=10)
  78. fig.autofmt_xdate()
  79. plt.plot(dates, highs, c='red', alpha=0.5)
  80. plt.plot(dates, lows, c='blue', alpha=0.5)
  81. plt.show()
  82.  
  83. city = input('输入城市名:')
  84. printWeatherInfo(getWeatherInfo(city))
  85. printTemperatures(getTemperatures(city))
  86. 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. npm安装时-S -D作用及区别

    -S 即--save(保存) 包名会被注册在package.json的dependencies里面,在生产环境下这个包的依赖依然存在 -D 即--dev(生产) 包名会被注册在package.json ...

  2. jQuery事件(四)

    一.基本事件函数下面事件函数中参数相关说明:eventType:事件类型,字符串'click' 'submit'多个事件类型可以通过用空格隔开[一次性绑定'click submit']eventDat ...

  3. Java 之 Arrays 类

    一.概述 java.util.Arrays 此类包含用来操作数组的各种方法.比如排序和搜索等,其所有方法均为静态方法,调用非常方便. 二.操作数组的方法 (1)使用二分搜索法来搜索指定的 int 型数 ...

  4. 英语apyrite红碧玺apyrite单词

    红碧玺(apyrite)是粉红.桃红.玫瑰红.深红.紫红等以红色调为主的碧玺,矿物学上主要属于锂电气石和镁电气石.红色起因可能与微量锰及锂和铯有关. 红色是碧玺中价值最高的,其中以紫红色和玫瑰红色最佳 ...

  5. Java String 字符串

    equals 字符串比较 String str = "furong"; String str1 = new String("furong"); System.o ...

  6. SparkStreaming之checkpoint检查点

    一.简介 流应用程序必须保证7*24全天候运行,因此必须能够适应与程序逻辑无关的故障[例如:系统故障.JVM崩溃等].为了实现这一点,SparkStreaming需要将足够的信息保存到容错存储系统中, ...

  7. z = z*z + c的分型图如何画

    使用python的图形库. 环境:conda+jupyter notebook 代码如下: import numpy as np from PIL import Image from numba im ...

  8. Httpd服务入门知识-Httpd服务常见配置案例之设定默认字符集

    Httpd服务入门知识-Httpd服务常见配置案例之设定默认字符集 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.查看生产环境中使用的字符集案例 1>.查看腾讯设置的默认 ...

  9. HDU3338 Kakuro Extension(最大流+思维构图)

    这道题一定要写一下,卡了好久. 题意: 有黑白两种方格,最上边一行和最左边一列一定是黑色,然后其余的地方有可能是黑色,有可能是白色,和白色相邻的黑色方格里有数字(1个或2个), 现在要求在白色方格里填 ...

  10. 《MVC架构下网站的设计与实现》论文笔记(十八)

    标题:MVC架构下网站的设计与实现 一.基本信息 时间:2017 来源:广东海洋大学数学与计算机学院 关键词:网站设计:MVC 框架:数据库:网络安全 二.研究内容 1.系统的整体架构设计(以广东海洋 ...