脚本超时
脚本超时错误是一种WebDriver 错误,当用户提供的脚本在会话的脚本超时持续时间到期之前未完成时发生。
脚本超时持续时间是一个可配置的功能,这意味着您可以更改驱动程序在中断注入的脚本之前等待的时间。驱动程序默认会等待 30 秒,然后中断脚本并返回脚本超时错误,但可以延长、缩短或设置为无限期。
如果使用 null
值将会话脚本超时持续时间设置为无限期,则您的会话有陷入不可恢复状态的风险。请注意,应谨慎使用此功能。
示例
考虑以下异步脚本,该脚本将在 35 秒后解析 promise 或调用回调
python
from selenium import webdriver
from selenium.common import exceptions
session = webdriver.Firefox()
try:
session.execute_script("""
let [resolve] = arguments;
setTimeout(resolve, 35000);
""")
except exceptions.ScriptTimeoutException as e:
print(e.message)
输出
ScriptTimeoutException: Timed out after 35000 ms
但是,如果您期望脚本需要更长时间才能完成,则可以使用功能来延长会话的默认脚本超时。
python
from selenium import webdriver
from selenium.common import exceptions
session = webdriver.Firefox(capabilities={"alwaysMatch": {"timeouts": {"script": 150000}}})
session.execute_script("""
let [resolve] = arguments;
setTimeout(resolve, 35000);
""")
print("finished successfully")
输出
finished successfully
另见
- WebDriver 错误列表
- 相关命令和类型