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('广州')

效果演示:

相关文章

安装python时MySQLdb报错的问题描述及解决方法

问题描述: windows安装python mysqldb时报错python version 2.7 required,which was not found in the regist...

用Python实现通过哈希算法检测图片重复的教程

用Python实现通过哈希算法检测图片重复的教程

Iconfinder 是一个图标搜索引擎,为设计师、开发者和其他创意工作者提供精美图标,目前托管超过 34 万枚图标,是全球最大的付费图标库。用户也可以在 Iconfinder 的交易板...

Python如何通过subprocess调用adb命令详解

前言 本文主要给大家介绍了关于使用Python通过subprocess调用adb命令,subprocess包主要功能是执行外部命令(相对Python而言)。和shell类似。 换言之除...

Python提取Linux内核源代码的目录结构实现方法

今天用Python提取了Linux内核源代码的目录树结构,没有怎么写过脚本程序,我居然折腾了2个小时,先是如何枚举出给定目录下的所有文件和文件夹,os.walk可以实现列举,但是os.w...

python中pygame模块用法实例

python中pygame模块用法实例

本文实例讲述了python中pygame模块用法,分享给大家供大家参考。具体方法如下: import pygame, sys from pygame.locals import *...