Python 网页变化监控脚本:实时检测更新并发送邮件通知
以下是一个简单的 Python 代码示例,可以监控一个网页的变化,并在页面内容发生变化时发送电子邮件通知。该代码还包括各种错误和异常检测,以确保其正常运行。
import urllib.request
import time
import smtplib
from email.mime.text import MIMEText
# 设置要监控的网页 URL 和检测时间间隔
url_to_monitor = 'https://example.com'
interval = 60 # 单位为秒
# 设置电子邮件通知相关参数
smtp_server = 'smtp.example.com'
smtp_port = 587
smtp_username = 'your_username'
smtp_password = 'your_password'
from_email = 'your_email@example.com'
to_email = 'recipient@example.com'
# 初始化上一次检测到的页面内容
last_content = ''
while True:
try:
# 发送 HTTP 请求并获取页面内容
response = urllib.request.urlopen(url_to_monitor)
content = response.read()
# 检查页面内容是否发生变化
if content != last_content:
# 如果内容发生变化,发送电子邮件通知
message = MIMEText('The monitored web page has changed.')
message['Subject'] = 'Web page update notification'
message['From'] = from_email
message['To'] = to_email
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(smtp_username, smtp_password)
server.sendmail(from_email, to_email, message.as_string())
# 更新上一次检测到的页面内容
last_content = content
# 等待指定的时间间隔
time.sleep(interval)
except Exception as e:
# 如果发生任何错误或异常,打印错误信息并等待一段时间后重试
print('An error occurred:', e)
time.sleep(interval)
此代码使用 Python 的 urllib.request 模块发送 HTTP 请求,并使用 time 模块控制检测时间间隔。它还使用 smtplib 模块发送电子邮件通知,并使用 MIMEText 类构造电子邮件消息。最后,它使用异常处理机制来捕获任何错误或异常,并在发生错误时等待一段时间后重试。
原文地址: https://www.cveoy.top/t/topic/lDUh 著作权归作者所有。请勿转载和采集!