最新文章专题视频专题问答1问答10问答100问答1000问答2000关键字专题1关键字专题50关键字专题500关键字专题1500TAG最新视频文章推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37视频文章20视频文章30视频文章40视频文章50视频文章60 视频文章70视频文章80视频文章90视频文章100视频文章120视频文章140 视频2关键字专题关键字专题tag2tag3文章专题文章专题2文章索引1文章索引2文章索引3文章索引4文章索引5123456789101112131415文章专题3
当前位置: 首页 - 科技 - 知识百科 - 正文

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

来源:动视网 责编:小采 时间:2020-11-27 14:35:08
文档

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

python结合API实现即时天气信息:python结合API实现即时天气信息 import urllib.request import urllib.parse import json 利用最美天气抓取即时天气情况 http://www.zuimeitianqi.com/ class ZuiMei(): def __init__(self): s
推荐度:
导读python结合API实现即时天气信息:python结合API实现即时天气信息 import urllib.request import urllib.parse import json 利用最美天气抓取即时天气情况 http://www.zuimeitianqi.com/ class ZuiMei(): def __init__(self): s
 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结合API实现即时天气信息

python结合API实现即时天气信息:python结合API实现即时天气信息 import urllib.request import urllib.parse import json 利用最美天气抓取即时天气情况 http://www.zuimeitianqi.com/ class ZuiMei(): def __init__(self): s
推荐度:
  • 热门焦点

最新推荐

猜你喜欢

热门推荐

专题
Top