You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python+Selenium如何在异常触发时截图并通过邮件发送

Selenium异常自动截图并邮件发送实现方案

前置依赖导入

需先引入相关依赖模块:

from selenium.common.exceptions import NoSuchElementException
from email.mime.image import MIMEImage
import datetime
import os

方案1:截图存储到本地(兼容性好,支持历史回溯)

修改异常捕获逻辑

def myfunction(self):
    try:
        # 原有业务代码
        pass
    except NoSuchElementException:
        print("error appeared")
        # 生成带时间戳的截图路径,避免文件覆盖
        screenshot_dir = "./error_screenshots"
        os.makedirs(screenshot_dir, exist_ok=True)
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        screenshot_path = f"{screenshot_dir}/error_{timestamp}.png"
        # 调用selenium接口存截图,driver为你初始化的浏览器驱动对象,按实际变量名调整
        self.driver.get_screenshot_as_file(screenshot_path)
        
        subject = "脚本执行异常告警"
        message = f"脚本触发NoSuchElementException,异常发生时间:{timestamp},错误截图见附件。"
        # 发送邮件时传入截图路径
        self.sendEmailBOTS(self.errorReportemail, self.errorReportemailpasswd, self.errorReportemail, subject, message, screenshot_path)
        for mail in self.ccBots:
            self.sendEmailBOTS(self.errorReportemail, self.errorReportemailpasswd, mail, subject, message, screenshot_path)

修改邮件发送函数,支持附件加载

def sendEmailBOTS(self, email, password, send_to, subject, message, screenshot_path=None):
    print("Sending email to", send_to)
    logging.info("Sending email to %s", send_to)
    msg = MIMEMultipart()
    msg["From"] = email
    msg["To"] = send_to
    msg["Subject"] = subject
    # 新增utf-8编码避免中文乱码
    msg.attach(MIMEText(message, 'plain', 'utf-8'))
    
    # 存在有效截图时追加为附件
    if screenshot_path and os.path.exists(screenshot_path):
        with open(screenshot_path, 'rb') as f:
            img = MIMEImage(f.read())
            img.add_header('Content-Disposition', 'attachment', filename=os.path.basename(screenshot_path))
            msg.attach(img)
    
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(email, password)
    text = msg.as_string()
    server.sendmail(email, send_to, text)
    server.quit()

方案2:不存本地,直接传二进制截图(节省存储空间)

修改异常捕获逻辑

def myfunction(self):
    try:
        # 原有业务代码
        pass
    except NoSuchElementException:
        print("error appeared")
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        # 直接获取二进制截图流,不写入本地磁盘
        screenshot_bytes = self.driver.get_screenshot_as_png()
        screenshot_name = f"error_{timestamp}.png"
        
        subject = "脚本执行异常告警"
        message = f"脚本触发NoSuchElementException,异常发生时间:{timestamp},错误截图见附件。"
        # 发送邮件时传入二进制流和截图文件名
        self.sendEmailBOTS(self.errorReportemail, self.errorReportemailpasswd, self.errorReportemail, subject, message, screenshot_bytes, screenshot_name)
        for mail in self.ccBots:
            self.sendEmailBOTS(self.errorReportemail, self.errorReportemailpasswd, mail, subject, message, screenshot_bytes, screenshot_name)

修改邮件发送函数

def sendEmailBOTS(self, email, password, send_to, subject, message, screenshot_bytes=None, screenshot_name="error_screenshot.png"):
    print("Sending email to", send_to)
    logging.info("Sending email to %s", send_to)
    msg = MIMEMultipart()
    msg["From"] = email
    msg["To"] = send_to
    msg["Subject"] = subject
    msg.attach(MIMEText(message, 'plain', 'utf-8'))
    
    # 存在二进制截图流时追加为附件
    if screenshot_bytes:
        img = MIMEImage(screenshot_bytes)
        img.add_header('Content-Disposition', 'attachment', filename=screenshot_name)
        msg.attach(img)
    
    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(email, password)
    text = msg.as_string()
    server.sendmail(email, send_to, text)
    server.quit()

注意:如果使用Gmail发送邮件,需要先开启账号两步验证,生成专属应用密码用于SMTP登录,直接使用账号原密码会触发权限校验失败。

内容的提问来源于stack exchange,提问作者Dilshan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 04:27:03