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

如何在Selenium中添加显式等待?优化ServiceNow数据导出脚本

用Selenium显式等待替代time.sleep实现ServiceNow数据导出自动化

核心修改思路

用Selenium的WebDriverWait结合预期条件(expected_conditions)替代固定时长的time.sleep(),确保目标元素加载完成后再执行后续操作,提升脚本稳定性和效率。

新增依赖导入

首先需要导入显式等待相关模块:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

修改后的完整代码

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 自定义显式等待方法,替代time.sleep
def wait_for_condition(driver, condition, timeout=10):
    return WebDriverWait(driver, timeout).until(condition)

sn_web = "https://your-instance.service-now.com"

while True:
    # 初始化driver(根据你的浏览器类型调整,比如Chrome/Firefox)
    driver = webdriver.Chrome()
    driver.get(sn_web)
    driver_action = ActionChains(driver)

    sn_js = """
    let output = '';
    let regex = new RegExp('macroponent*')
    for (let i of document.querySelectorAll('*')) {
        if (regex.test(i.localName)) {
            output = i.localName;
        }
    }
    return document.querySelector(output).shadowRoot.querySelector('iframe');
    """

    try:
        # 等待第一个iframe加载完成,再切换上下文
        wait_for_condition(driver, EC.frame_to_be_available_and_switch_to_it((By.TAG_NAME, "iframe")))
        # 等待目标图标可点击后执行点击
        target_icon = wait_for_condition(driver, EC.element_to_be_clickable((By.TAG_NAME, "i")))
        target_icon.click()
        # 切回主文档上下文
        driver.switch_to.default_content()
    except Exception as e:
        print(f"初始操作失败: {e}")
        driver.quit()
        continue
    else:
        # 等待Shadow DOM内的目标iframe加载完成
        incident_name_web_ele = wait_for_condition(
            driver,
            lambda d: d.execute_script(sn_js) is not None,
            timeout=20
        )
        driver.switch_to.frame(incident_name_web_ele)

        # 等待Export相关元素加载完成
        export_ele = wait_for_condition(
            driver,
            EC.presence_of_all_elements_located((By.CLASS_NAME, "context_item"))
        )
        # 悬停到最后一个context_item(Export按钮)
        driver_action.move_to_element(export_ele[-1]).perform()

        # 等待CSV选项出现后执行点击JS
        wait_for_condition(
            driver,
            EC.presence_of_element_located((By.XPATH, "//*[contains(text(), 'CSV')]"))
        )
        find_csv_js = """
        let regex = new RegExp('CSV')
        for (let i of document.getElementsByClassName('context_item')) {
            if (regex.test(i.innerHTML)) {
                i.click()
            }
        }
        """
        driver.execute_script(find_csv_js)

        # 等待导出对话框全局对象初始化完成
        wait_for_condition(
            driver,
            lambda d: d.execute_script("return typeof g_export_schedule_dialog !== 'undefined'"),
            timeout=30
        )
        driver.execute_script("g_export_schedule_dialog.waitForIt();")

        # 等待导出任务完成
        wait_for_condition(
            driver,
            lambda d: d.execute_script("return typeof g_poll_dialog !== 'undefined' && g_poll_dialog.isComplete()"),
            timeout=120
        )
        driver.execute_script("g_poll_dialog.getResult();")

        # 等待下载完成(可根据实际需求优化为文件监控逻辑)
        wait_for_condition(driver, lambda d: True, timeout=40)

        driver.quit()
        break

关键改动说明

  1. 替换固定等待为显式等待:自定义wait_for_condition方法,根据不同场景等待元素的可见性、可点击性或存在性,避免不必要的等待时间。
  2. 优化iframe切换逻辑:用EC.frame_to_be_available_and_switch_to_it等待iframe加载完成再切换,确保上下文正确。
  3. JS执行前置校验:执行自定义JS前,先通过显式等待确保目标元素(如Shadow DOM内的iframe、全局JS对象)已存在,避免脚本报错。
  4. 元素交互优化:优先使用Selenium原生的元素定位和点击方法,比直接执行JS更稳定,必要时再用JS辅助。

注意事项

  • 根据你的ServiceNow实例页面结构,调整元素定位方式(如XPATH、CLASS_NAME)。
  • 可根据实际网络速度和页面加载速度,调整timeout参数(默认10秒,复杂操作可设为20-120秒)。
  • 若需校验下载文件是否完成,可以结合文件系统监控(如检查下载目录中目标文件是否存在且大小稳定)进一步优化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:23:19