> 백엔드 개발 > 파이썬 튜토리얼 > python结合API实现即时天气信息

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

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
풀어 주다: 2016-06-10 15:06:43
원래의
1404명이 탐색했습니다.

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

로그인 후 복사

效果演示:

관련 라벨:
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿