Python實現微信定時發送天氣預報


 

schedule實現定時

 

 1 import requests
 2 from requests import exceptions
 3 from urllib.request import urlopen
 4 from bs4 import BeautifulSoup
 5 import re
 6 from wxpy import *
 7 import  schedule
 8 import  time
 9  
10  
11 bot=Bot(cache_path=True) #登陸網頁微信,並保存登陸狀態
12  
13 def sendblogmsg(content):
14     #搜索自己的好友,注意中文字符前需要+u
15     my_friend = bot.friends().search(u'卿塵')[0]
16     my_friend.send(content)
17     #my_group = bot.groups().search(u'卿塵')[0]
18     #my_group.send(content) #發送天氣預報
19  
20 def job():
21     resp=urlopen('http://www.weather.com.cn/weather/101010100.shtml')
22     soup=BeautifulSoup(resp,'html.parser')
23     tagToday=soup.find('p',class_="tem")  #第一個包含class="tem"的p標簽即為存放今天天氣數據的標簽
24     try:
25         temperatureHigh=tagToday.span.string  #有時候這個最高溫度是不顯示的,此時利用第二天的最高溫度代替。
26     except AttributeError as e:
27         temperatureHigh=tagToday.find_next('p',class_="tem").span.string  #獲取第二天的最高溫度代替
28  
29     temperatureLow=tagToday.i.string  #獲取最低溫度
30     weather=soup.find('p',class_="wea").string #獲取天氣
31     contents = '北京' + '\n' +  '最高溫度:' + temperatureHigh + '\n' + '最低溫度:' + temperatureLow + '\n' +  '天氣:' + weather 
32        # result3 = '最低溫度:' + temperatureLow
33     #print('最低溫度:' + temperatureLow)
34     #print('最高溫度:' + temperatureHigh)
35    # print('天氣:' + weather)
36     sendblogmsg(contents)
37 #定時
38 schedule.every().day.at("19:20").do(job) #規定每天12:30執行job()函數
39 while True:
40     schedule.run_pending()#確保schedule一直運行
41     time.sleep(1)
42 bot.join() #保證上述代碼持續運行

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM