python實現通過微信每天給女友發天氣預報(超簡單程式碼+itchat+入門級爬蟲)
1.前言
剛學爬蟲想寫個最簡單的小程式體會一下爬蟲的效果,原理程式碼非常簡單,僅供大家學習~
2.前期準備
(1).itchat
itchat是一個非常方便簡單的python的微信介面,可以傻瓜一樣的登陸微信,傳送訊息傳送圖片等,這裡我只用到了最簡單的登陸登出和send方法。
auto_login可以讓使用者執行登陸,執行後效果就是展示一個二維碼讓你去掃,我發現每次執行一遍都要掃一遍很麻煩,查資料發現寫一個hotReload=True即可無需再次掃碼很方便。
auto_login(hotReload=True)
登陸成功會有如下顯示
登出操作很簡單,不多說了,習慣性的加上
logout()
重點來了send函式的使用send(msg=message,toUserName = userName)
msg為想傳送的資訊,userName為使用者的一個編號,注意這個不是所謂的微訊號或者暱稱,開始用微訊號當userName發現不對,解決方法如下users = ic.search_friends(name = 'yl')
userName = users[0]['UserName']
先search一下,這時候的name就寫你給他的備註就好,然後再讀一下他的UserName就好了,有興趣的可以print一下,是一大長串十六進位制數
要注意的是,send函式返回一個值,如果send成功即返回True,失敗即返回False。可以用它來檢測一下是否傳送成功。
千萬不要嘗試把send放進for迴圈!!我想呼死我室友的時候,發了一百多條就被微信封了幾個小時不能發訊息!!!血的教訓。。。
(2).爬蟲
只學了一天爬蟲,所以還不是很懂,以後會寫幾篇詳細的關於爬蟲的東西,今天只說說最簡單的應用
http://tianqi.sogou.com/changchun/想爬這個網站的天氣,右鍵檢視原碼發現寫的很簡單啊。。。所以就成功爬了它。說一下方法:
(1).先安裝 urllib和BeautifulSoup
(2).urlopen
html=urllib.request.urlopen("http://tianqi.sogou.com/changchun/")
用這個函式來開啟網頁↑,把它當做物件,這樣就可以對他進行一系列操作了
(3).提取資訊
我發現有關天氣溫度和日期的資訊都屬於p標籤,並且class都是p1,那就很方便了,呼叫這個函式
bs0bj = BeautifulSoup(html)
nameList = bs0bj.findAll("p",{"class":"p1"})
以字典形式寫的。這樣把class為P1,並且都是P類標籤的全部放進了nameList數組裡,列印一下他吧,列印成功就證明已經爬成功啦
爬蟲這一塊今天看了幾個入門函式,就想小試牛刀一下,爬起來很順利,更詳細的會再寫幾篇blog學習
(3).附上原始碼
兩個檔案,第一個寫爬蟲,第二個寫微信傳送訊息
主函式:
from urllib.request import urlopen
from bs4 import BeautifulSoup
def getMessage():
html=urlopen("http://tianqi.sogou.com/changchun/")
bs0bj = BeautifulSoup(html)
nameList = bs0bj.findAll("p",{"class":"p1"})
count = 0
weather=[]
for name in nameList:
count+=1
weather.append(name.get_text())
if(count==3):
break
return weather
if __name__ == "__main__":
weather = getMessage()
print(weather)
import itchat as ic
import time
from Getmessage import getMessage
from getTime import startPro
count = 0
try:
weatherInformation=getMessage()
Date = weatherInformation[0]
weather = weatherInformation[1]
temper = weatherInformation[2]
message=Date+"\n"+weather+"\n"+temper+"\n"
print(message)
except:#丟擲異常
message = ""
print("Get message failed")
ic.auto_login(hotReload=True)
users = ic.search_friends(name = 'yl')
userName = users[0]['UserName']
ret = ic.send(msg=message,toUserName = userName)
if ret:
print("Succeed Sending")
else:
print("Error sending")
time.sleep(60)
ic.logout()
(4).定時
定時傳送,不需要多說了,入門級別的語句,直接貼程式碼吧,又寫在另一個檔案了
import time
def startPro():
while(1):
currentHour = int(time.strftime("%H"))
print(currentHour)
if currentHour==7:
print("It's time")
break
if currentHour == 6:
print("itstimerightnow")
time.sleep(60)
else:
print("It's not time ,sleep........")
time.sleep(3500)
if __name__ == "__main__":
startPro()
(5).結語
這個程式可以改動的東西太多了,程式碼也不是很精煉完善,而且可以爬一下建議的著裝,是否帶傘,是否適宜出行這一類資訊,然後我會把它放進樹莓派中,每天就可以進行推送啦(PC也可以的)……過一陣更新一下
祝大家早日脫單