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

yipeiwu_com5年前Python基础

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/queryWeather'
  self.headers = {}
  self.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'
  # 部分城市的id信息
  self.cities = {}
  self.cities['成都'] ='01012703'
  self.cities['杭州'] = '01013401'
  self.cities['深圳'] = '01010715'
  self.cities['广州'] = '01010704'
  self.cities['上海'] = '01012601'
  self.cities['北京'] = '01010101'
  # Form Data
  self.data = {}
  self.city = '北京'
  
 def query(self,city='北京'):
  if city not in self.cities:
   print('暂时不支持当前城市')
   return
  self.city = city
  data = urllib.parse.urlencode({'cityCode':self.cities[self.city]}).encode('utf-8')
  req = urllib.request.Request(self.url,data,self.headers)
  response = urllib.request.urlopen(req)
 
  html = response.read().decode('utf-8')
  # 解析json数据并打印结果
  self.json_parse(html)
 
 def json_parse(self,html):
  target = json.loads(html)
  high_temp = target['data'][0]['actual']['high']
  low_temp = target['data'][0]['actual']['low']
  current_temp = target['data'][0]['actual']['tmp']
  today_wea = target['data'][0]['actual']['wea']
  air_desc = target['data'][0]['actual']['desc']
  # 上海 6~-2°C 现在温度 1°C 湿度:53 空气质量不好,注意防霾。 
  print('%s: %s~%s°C 现在温度 %s°C 湿度:%s %s'%(self.city,high_temp,low_temp,current_temp,today_wea,air_desc))

if __name__ == '__main__':
 zuimei = ZuiMei()
 zuimei.query('广州')

效果演示:

相关文章

TensorFlow实现Softmax回归模型

一、概述及完整代码 对MNIST(MixedNational Institute of Standard and Technology database)这个非常简单的机器视觉数据集,T...

python读取Excel实例详解

本文实例为大家分享了python读取Excel实例的具体代码,供大家参考,具体内容如下 1.操作步骤: (1)安装python官方Excel库-->xlrd (2)获取Excel文...

Python中使用logging和traceback模块记录日志和跟踪异常

Python中使用logging和traceback模块记录日志和跟踪异常

logging模块 logging模块用于输出运行日志,可以设置不同的日志等级,保存信息到日志文件中等。 相比print,logging可以设置日志的等级,控制在发布版本中的输出内容,并...

Python django框架应用中实现获取访问者ip地址示例

Python django框架应用中实现获取访问者ip地址示例

本文实例讲述了Python django框架应用中实现获取访问者ip地址。分享给大家供大家参考,具体如下: 在django官方文档中有一段对request.META的解释: HttpR...

利用Python实现kNN算法的代码

邻近算法(k-NearestNeighbor) 是机器学习中的一种分类(classification)算法,也是机器学习中最简单的算法之一了。虽然很简单,但在解决特定问题时却能发挥很好的...