因为近期需要时刻查看该网页的最新公布消息,所以使用python自动访问网页消息并通过邮件通知。
官网链接:硕士招生 - 西北政法大学研究生院
工具:python,官网下载python安装即可
插件安装:
pip install BeautifulSoup4
pip install requests
需要邮件的发件人账号信息,邮箱要用授权码作为密码。
执行脚本:
处理逻辑:使用request请求得到页面交给bs4处理,得到标题和链接,日期,内容。配置发件函数,手工建立title.txt文件在脚本的目录,用于保存上一次最新的消息标题,用最新标题的时间和今日时间进行对比,一致后再对比与上一个标题是否一致,不一致发送邮件。
import smtplib
from email.mime.text import MIMEText
import requests
import time
from bs4 import BeautifulSoupheaders = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36"
}url = "https://grs.nwupl.edu.cn/info/iList.jsp?cat_id=10503"
resp = requests.get(url, headers=headers)
resp.encoding = "UTF-8"
resp.close()# 把首页源代码交给bs处理,得到标题和链接
main_page = BeautifulSoup(resp.text, "html.parser")
news_title_list = main_page.find("h1", class_="am-text-truncate").findAll("span")# 最新消息日期
news_time = main_page.find("div", class_="time").text
# 最新消息标题
news_title = news_title_list[0].text
# 最新消息内容
news_content = main_page.find("div", class_="am-u-md-10 am-u-sm-7 am-padding-right-0").find("p").textdef send_mail(title, news_time, content):# 发件人邮箱地址sendAddress = 'xxx@qq.com'# 发件人授权码password = 'xxx'# 连接服务器server = smtplib.SMTP_SSL('smtp.qq.com', 465)# 登录邮箱server.login(sendAddress, password)# 正文# content = "test"# 定义一个可以添加正文的邮件消息对象msg = MIMEText(content, 'plain', 'utf-8')# 发件人昵称和地址msg['From'] = 'xxx@qq.com'# 收件人昵称和地址# msg['To'] = 'xxx<xxx@qq.com>;xxx<xxx@qq.com>'msg['To'] = 'xxx@163.com'# 邮件主题msg['Subject'] = f"{title}-{news_time}"server.sendmail(sendAddress, ['xxx@163.com'], msg.as_string())print('邮件发送成功')# 最新消息和今天日期比对
news_time_tuple = time.strptime(news_time, "%Y-%m-%d")
news_timestamp = time.mktime(news_time_tuple)
today_format = f"{time.localtime().tm_year}-{time.localtime().tm_mon}-{time.localtime().tm_mday}"
today_time_tuple = time.strptime(today_format, "%Y-%m-%d")
today_timestamp = time.mktime(today_time_tuple)if news_timestamp == today_timestamp:# print("时间一致,再比较上一次的标题是否一致")with open("./title.txt", mode="r", encoding='utf-8') as f:old_title = f.read()print(f"上个消息标题:{old_title},新消息标题:{news_title}")if old_title == news_title:print("标题一致,没有新闻更新,不发送邮件")else:print("标题不一致,有内容更新,发送邮件")# 保存新消息标题至文本with open("./title.txt", mode="wb") as f_new:f_new.write(news_title.encode("utf-8"))send_mail(news_title, news_time, news_content)
else:print("时间不一致,不做操作")