gpt4 book ai didi

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

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 25 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章python结合API实现即时天气信息由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
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实现即时天气信息的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com