python爬蟲實作對年級網站通知的自動化推送
- 前言
- 原理
- 函式庫
- 安裝方法
- 函式
- 原始碼
- 云服務器定時計劃
- 效果
前言
這個代碼專案的誕生來源于我自己的懶惰,我們學院有自己的年級網站(以下簡稱級網),因此很多重要通知會在網站發布,雖然作為網站維護者的我因為日常 學習生活事情繁瑣,加上級網通知很多時候都是不定時不定量的發,我也因為自己懶于看級網通知導致經常錯過和自己有關的通知,因此產生了想寫一個爬蟲來替我完成看級網有沒有新的通知并提醒我的任務,
原理
利用requests庫對指定網站發起請求,并加載資源到本地,利用BeautifulSoup庫對加載的資源進行檢索、切片、貼合等操作,首先找到對應的文章標題標簽,并獲取鏈接和標簽內容,再找到文章發布時間的標簽并和標題系結,判斷發布時間和當前日期是否一致,一致則向微信和郵箱推送內容,不一致則不進行任何操作,
函式庫
import time
import datetime
import urllib.request
import requests
import json
from bs4 import BeautifulSoup
import smtplib
from email import (header)
from email.mime import (text, multipart)
安裝方法
pip install --upgrade pip
pip install beautifulsoup4
pip install requests
函式
1.模擬瀏覽器向網站發出請求并加載資源到本地
def getTitle (url):
headers = ('User-Agent',"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36")
opener = urllib.request.build_opener()
opener.addheaders = [headers]
urllib.request.install_opener(opener)
html = urllib.request.urlopen(url).read().decode('utf-8', 'ignore')
bs = BeautifulSoup(html,'html.parser')
Title_links = bs.select('特定標簽')
return Title_links
2.獲取當前日期
def getNowDate():
now_time = datetime.datetime.now()
yes_time = now_time+datetime.timedelta(days=-3)
current_time = yes_time.strftime('%Y-%m-%d')
return current_time
3.對所篩選出的資料進行整合
for link in linklist_Title:
contents.append(link.text.strip())
links.append(link.get('href'))
for date in linklist_Date:
dates.append(date.text.strip())
#獲取指定日期的文章資訊
for date,text, link, in zip(dates, contents, links):
data = date+' '+text+':http://xxx.xxx.com'+link
if date == Now_Date:
send_data = send_data+data+'\n\n'
4.群發郵件
def sender_mail():
smtp_Obj = smtplib.SMTP_SSL('smtp.qq.com',465) # 連接qq郵箱SMTP服務器,埠是465
sender_addrs = 'xxx@foxmail.com' # 發件人郵箱賬號
password = "uaxxxxxxxxxxxge" # 發件人郵箱密碼 即配置生成的授權碼
smtp_Obj.login(sender_addrs, password)
receiver_addrs = ['yyy@foxmail.com','zzz@foxmail.com'] #群發的收件人
for email_addrs in receiver_addrs:
try:
msg = multipart.MIMEMultipart()
msg['From'] = "InetGeek"
msg['To'] = email_addrs
msg['subject'] = header.Header('今日級網更新通知', 'utf-8')
msg.attach(text.MIMEText('今日:['+getNowDate()+']級網最新通知如下:\n\n'+send_data, 'plain', 'utf-8')) #郵件內容
smtp_Obj.sendmail(sender_addrs, email_addrs, msg.as_string()) # 發件人郵箱賬號、收件人郵箱賬號、發送郵件
print('成功發送給%s' % ( email_addrs))
except Exception as e:
continue
smtp_Obj.quit() #退出
5.用json格式向push+推送文章
token = '4bxxxxxxxxxxxxxxxxxxxxxxx5'
title= '今日級網更新通知'
content = send_data
url = 'http://pushplus.hxtrip.com/send'
data = {
"token":token,
"title":title,
"content":content
}
body=json.dumps(data).encode(encoding='UTF-8')
headers = {'Content-Type':'application/json'}
requests.post(url,data=body,headers=headers)
原始碼
gihub倉庫:InetGeek
云服務器定時計劃
定時執行shell指令
/usr/bin/python /www/server/panel/class/Notice_Spider.py
博客:Digran’s Blog
效果
1.微信端

2.QQ郵件端

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/272887.html
標籤:python
下一篇:使用PyCharm批量爬取小說
