typecho开发板更新提醒python脚本

更新了文件判断

# -*- coding: utf-8 -*-
import requests
from bs4 import BeautifulSoup
import re
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

my_sender='1111@529i.com'    # 发件人邮箱账号
my_pass = 'st555qohpabjja'              # 发件人邮箱密码(当时申请smtp给的口令)
my_user='1111@qq.com'      # 收件人邮箱账号,我这边发送给自己
url='http://typecho.org/download'
headers = {'user-agent':'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'}
#获取版本
res=requests.get(url, headers).text
soup = BeautifulSoup(res, 'html.parser')
tags = soup.find('div',{'class':'post-content fmt'})
a = tags.find('a',attrs={"href":re.compile(r'^https:')})
link = 'GitHub地址:' + a.get('href')
text = '版本号:' +  a.get_text()
url1 =  a.get('href')
#更新时间
resp = requests.get(url=url1, headers=headers).text
soup1 = BeautifulSoup(resp,'html.parser')
#div = soup1.find('div',{'class':'flex-self-start no-wrap'})
div = soup1.find('relative-time')
time = '更新时间:' + div.get_text() 
#print(text)
try:    #判断文件是否存在
    f = open("test.txt")
    f.close()
except IOError:
    f = open("test.txt",'w')
    f.write(str(a.get_text()))
    f.close()
    print ("第一次运行写入版本号成功")
fp = open("test.txt",'r')
txt = fp.read()
fp.close()
#判断版本号
if txt == a.get_text():   
    print('未更新')

else:
    fp = open("test.txt",'w+')
    fp.write(str(a.get_text()))
    fp.close()
    print("有新版")
    
    #smtp发信
    ret=True
    try:
        msg=MIMEText('<p>' + (time) + '</p>' + '<p>' + (text) + '</p>' + '<p>' + (link) + '</p>','html','utf-8')
        msg['From']=formataddr(["发件人昵称",my_sender])  # 括号里的对应发件人邮箱昵称、发件人邮箱账号
        msg['To']=formataddr(["收件人昵称",my_user])              # 括号里的对应收件人邮箱昵称、收件人邮箱账号
        msg['Subject']="typecho升级提醒"                # 邮件的主题,也可以说是标题

        server=smtplib.SMTP_SSL("smtp.qq.com", 465)  # 发件人邮箱中的SMTP服务器,端口是465
        server.login(my_sender, my_pass)  # 括号中对应的是发件人邮箱账号、邮箱密码
        server.sendmail(my_sender,[my_user,],msg.as_string())  # 括号中对应的是发件人邮箱账号、收件人邮箱账号、发送邮件
        server.quit()# 关闭连接
    except Exception:# 如果 try 中的语句没有执行,则会执行下面的 ret=False
        ret=False

    if ret:
        print("邮件发送成功")
    else:
        print("邮件发送失败")
如果觉得我的文章对你有用,请随意赞赏