用 Python 的 Requests 写一个简单的网页更新检测脚本

这是一个简易的 Python 脚本,每隔一段时间获取页面,如果页面代码有变化,通过 SMTP 发信提醒你。仅适用于简单的页面。

import time
import requests
from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

import smtplib
        
def _format_addr(s):
    name, addr = parseaddr(s)
    return formataddr((Header(name, 'utf-8').encode(), addr))

def sendmail(msg):
    from_addr = '###'
    password = '###'
    to_addr = '###'
    smtp_server = '###'
    msg['From'] = _format_addr('python <%s>' % from_addr)
    msg['To'] = _format_addr('ning <%s>' % to_addr)
    msg['Subject'] = Header('页面有更新!', 'utf-8').encode()
    server = smtplib.SMTP(smtp_server, 25)
    ###server.set_debuglevel(1)
    server.login(from_addr, password)
    server.sendmail(from_addr, [to_addr], msg.as_string())
    server.quit()

timesleep=1
maxtime=1
url="###"
headers={'Accept-Language':'zh-Hans-CN, zh-Hans; q=0.5','User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362'}
a=requests.get(url,headers=headers)
time.sleep(timesleep)
count=0
while(count<maxtime):
    b=requests.get(url,headers=headers)
    print("Got it")
    if(a.text!=b.text):
        a=b
        msg = MIMEText(b.text, 'html', 'utf-8')
        print("Sending mail...")
        sendmail(msg)
        count=count+1
    time.sleep(timesleep)

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Back to Top