1. 程式人生 > >Python爬取天氣資訊並定時傳送給微信好友(異地戀神器)!!

Python爬取天氣資訊並定時傳送給微信好友(異地戀神器)!!

效果

前言

中國天氣網:

http://www.weather.com.cn/

點選右上角的具體的天氣資料

想獲取哪個城市的天氣,就搜尋城市進行切換

這裡以青島為例

可以看到此時url為:

http://www.weather.com.cn/weather1d/101120201.shtml

城市不同所以url不同,要改為自己想獲取的城市的url

實現

開啟IDLE,新建檔案weatherBot.py

程式碼:

import requests
from requests import exceptions
from urllib.request import urlopen
from bs4 import BeautifulSoup
from wxpy import *
import  time
from threading import Timer
 
 
bot=Bot() #登陸網頁微信,並儲存登陸狀態
 
def sendblogmsg(content):
    #搜尋自己的好友,注意中文字元前需要+u
 
    my_group = bot.friends().search('傳送好友的微信名')[0]
    my_group.send(content) #傳送天氣預報
 
def job():
    #要改為自己想要獲取的城市的url,下面是青島的url
    resp=urlopen('http://www.weather.com.cn/weather1d/101120201.shtml')
    soup=BeautifulSoup(resp,'html.parser')
    #獲取溫度資料
   tem=soup.find('p',class_="tem").find('span').string  #第一個包含class="tem"的p標籤即為存放今天天氣資料的標籤
    #獲取天氣狀況
   weather=soup.find('p',class_="wea").string
    #獲取風力情況
    win = soup.find('p',class_="win").find('span').string
    #獲取日出時間
    sun = soup.find('p',class_="sun sunUp").find('span').string
    #拼接要傳送的訊息格式
    contents = '青島今日:' +'\n' + '天氣:'+weather + '\n'+'溫度:'+tem+'℃'+ '\n'+'風力:'+win+ '\n'+sun +'\n'+'注意天氣變化!!'
    sendblogmsg(contents)
    #設定每隔30秒傳送一次,可以自己設定為一天的秒數
    t = Timer(30, job)
    t.start()

#定時
if __name__ == "__main__":
    job()

 

程式碼中獲取資料的格式,按F12,找到我們要爬取的資料。

儲存並按F5執行,此時會生成並彈出掃描登入網頁版微信的圖片,拿手機掃描後登陸即可。

網頁版微信不能與電腦端微信同時登入,但是可以與手機同時登入。

將程式碼部署在伺服器上,設定時間為一天的秒數,便能實現自動傳送天氣預報資訊。