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

Python Selenium处理异常与alert弹窗批量查询学生成绩问题

Selenium成绩批量查询统计代码修复

原代码核心问题

  • 调用switch_to_alert()时缺少驱动对象前缀,直接调用会触发未定义变量报错
  • 异常捕获逻辑包裹了整个循环,遇到一次异常就会终止所有学号的遍历,无法继续执行后续查询
  • 每次提交学号后未清空输入框,下一次输入会叠加旧内容,导致提交的学号全部错误
  • 从页面获取的成绩是字符串类型,直接和浮点数96.00比较会触发类型错误
  • 未区分无效学号弹出alert、有效学号弹出新窗口两种场景,逻辑判断混乱

修复后完整代码

from selenium import webdriver
from selenium.common.exceptions import NoAlertPresentException
import time

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-logging'])
# 注意修改为你本地的chromedriver路径
web = webdriver.Chrome(options=options, executable_path='J:\stuff\soft\chromedriver.exe')
web.get('https://msbte.org.in/DISRESLIVE2021CRSLDSEP/frmALYSUM21PBDisplay.aspx')

# 存储高分统计结果
resultCount = 0
rlstart = 156857
rlend = 157299
web.implicitly_wait(5)
# 保存主查询窗口句柄
main_window = web.current_window_handle

try:
    for x in range(rlstart, rlend):
        # 每次输入前清空输入框
        inp = web.find_element_by_xpath('//*[@id="txtEnrollSeatNo"]')
        inp.clear()
        inp.send_keys(str(x))
        submit = web.find_element_by_xpath('//*[@id="btnSubmit"]')
        submit.click()
        # 等待页面响应
        time.sleep(1)

        # 先判断是否弹出了无效学号的alert
        try:
            alert = web.switch_to.alert
            alert.accept()
            # 关闭alert后直接进入下一轮循环
            continue
        except NoAlertPresentException:
            # 没有alert说明是有效学号,判断是否打开了新窗口
            pass

        # 切换到新弹出的成绩窗口
        for handle in web.window_handles:
            if handle != main_window:
                web.switch_to.window(handle)
                # 获取成绩并转换为浮点数
                score_text = web.find_element_by_css_selector('body > div > div:nth-child(3) > div:nth-child(4) > table > tbody > tr:nth-child(5) > td:nth-child(3) > strong').text
                score = float(score_text.strip())
                if score > 96.00:
                    resultCount += 1
                # 关闭成绩窗口,切回主窗口
                web.close()
                web.switch_to.window(main_window)
                break

finally:
    print("查询结束,高于96分的人数:", resultCount)
    web.quit()

关键修改说明

  • 把alert判断逻辑放在循环内部,处理完无效学号的弹窗后直接进入下一轮遍历,不会中断整个查询流程
  • 每次输入学号前调用clear()清空输入框,保证提交的学号正确
  • 新增NoAlertPresentException捕获区分两种场景:有alert直接处理,没有alert再处理新窗口的成绩
  • 把页面获取的成绩字符串转换为浮点数再做大小比较,避免类型错误
  • 所有switch_to相关操作都加上驱动对象前缀web.,修复未定义变量报错
  • 切换到新窗口逻辑加上break,找到成绩窗口后直接停止遍历句柄,提升执行效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 00:45:00