import requests import json import time # address = input() # 輸入要查詢的地址 address = '湘潭市湖南科技大學' # 獲取輸入地址的經緯度 map_key = '騰訊地圖API key' map_url = 'https://apis.map.qq.com/ws/geocoder/v1/?address=' + address + '&key=' + map_key map_response = requests.get(map_url) map_json = json.loads(map_response.text) latitude = str(map_json['result']['location']['lat']) longitude = str(map_json['result']['location']['lng']) # print(address + longitude + latitude) # 根據經緯度查詢天氣 api_key = '彩雲天氣API key' # api秘鑰 json_url = 'https://api.caiyunapp.com/v2/' + api_key + '/' + longitude + ',' + latitude + '/realtime.json' json_response = requests.get(json_url) json_str = json.loads(json_response.text) timeStamp = json_str['server_time'] localTime = time.localtime(timeStamp) formatTime = time.strftime("%Y{y}%m{m}%d{d} %H{c}%M{mi}%S{s}").format(y='年', m='月', d='日', c='點', mi='分', s='秒') temperature = str(json_str['result']['temperature']) # 氣溫 humidity = json_str['result']['humidity'] # 濕度 skyconndition = str(json_str['result']['skycon']) # 天氣狀況 weatherdic = {'CLEAR_DAY': '晴', 'CLEAR_NIGHT': '晴', 'PARTLY_CLOUDY_DAY': '多雲', 'PARTLY_CLOUDY_NIGHT': '多雲', 'CLOUDY': '陰', 'WIND': '陰', 'HAZE': '霧霾', 'RAIN': '雨', 'SNOW': '雪'} skyconndition = weatherdic[skyconndition] # 匹配代碼與文字 aqi = str(json_str['result']['aqi']) # 空氣質量指數 if int(aqi) >= 200: aqi = '200 \n霧霾天要少出去玩哦' # pm25 = str(json_str['result']['pm25']) real_humidity = str(humidity * 100) current_weather = address + '\n北緯' + str(latitude) + ' 東經' + str( longitude) + '\n實時天氣:\n氣溫:' + temperature + '℃\n濕度:' + real_humidity + '%\n天氣:' + skyconndition + '\nAQI:' + aqi + '\n時間:' + formatTime print(current_weather) def weather(): headers = {"Content-Type": "text/plain"} # 蘇寧接口獲取時間 # timeUrl = 'http://quan.suning.com/getSysTime.do' # timeResponse = requests.get(timeUrl) # timeJson = json.loads(timeResponse.text) # severTime = timeJson['sysTime2'] # 2020-02-21 12:26:12 s = current_weather data = { "msgtype": "text", "text": { "content": s, } } r = requests.post( url='http://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=企業微信機器人key', # webhook地址 headers=headers, json=data) print(r.text) weather()