1. 程式人生 > 程式設計 >python使用itchat模組給心愛的人每天發天氣預報

python使用itchat模組給心愛的人每天發天氣預報

本文例項為大家分享了python給心愛的人每天發天氣預報的具體程式碼,供大家參考,具體內容如下

下面的程式碼實現了用了之前獲取天氣的程式碼,然後用itchat模組

給指定的人傳送訊息

程式碼比較簡單,改一下CITY_NAME和name個傳送語句直接就可以用

import requests
import json
import itchat
from threading import Timer

global CITY_NAME
CITY_NAME = "北京"
headers = {
 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/78.0.3904.70 Safari/537.36'
}


def find_weather():
 # 獲取天氣
 weather_url = 'http://wthrcdn.etouch.cn/weather_mini?city={}'.format(CITY_NAME)
 city_response = requests.get(weather_url,headers=headers)
 return json.loads(city_response.text)


def reform_fl(str_fl):
 new_str = str_fl.split("[")[2].split("]")[0]
 if new_str.startswith("<"):
  result = new_str.split("<")[1]
 else:
  result = new_str
 return result


def send_news(str):

 itchat.auto_login() # 彈出一張圖片二維碼,掃描登入網頁微信
 person= itchat.search_friends(name='一隻可愛的小奶貓') # 選擇給誰傳送,name是他的備註
 mylover = person[0]["UserName"]
 itchat.send(str,toUserName=mylover)
 Timer(86400,send_news).start() # 每隔86400秒傳送一次,每天發一次


if __name__ == "__main__":

 weather_info = find_weather()
 forecast_weather = weather_info.get('data').get('forecast')
 ganmao = weather_info.get('data').get('ganmao')
 str_1 = '今天是:' + forecast_weather[0].get('date') + '\n' \
   + '最高溫度:' + forecast_weather[0].get('high') + '\n' \
   + '最低溫度:' + forecast_weather[0].get('low') + '\n' \
   + '風向:' + forecast_weather[0].get('fengxiang') + '\n' \
   + '風力:' + reform_fl(forecast_weather[0].get('fengli')) + '\n' \
   + '天氣狀況:' + forecast_weather[0].get('type') + '\n'
 str_2 = "早安親愛滴:%s\n%s最近%s" % (str_1,CITY_NAME,ganmao)
 send_news(str_2)

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。