如何设置 Selenium Python WebDriver 默认超时?
seleniumautomation testingtesting toolspython
我们可以使用 Selenium webdriver 设置默认超时。方法 set_page_load_timeout 用于设置页面加载超时。等待时间(以秒为单位)作为参数传递给该方法。
语法
driver.set_page_load_timeout(5)
如果等待时间过后页面仍未加载,则会抛出 TimeoutException。
我们可以在同步中使用 implicit wait 概念来定义默认超时时间。这是一个全局等待时间,应用于页面中的每个元素。方法 implicitly_wait 用于定义隐式等待。等待时间(以秒为单位)作为参数传递给该方法。
语法
driver.implicitly_wait(5);
如果隐式等待时间过去后页面仍未加载,则会抛出 TimeoutException。
示例
使用 set_page_load_timeout() 实现代码
from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\chromedriver.exe") # set_page_load_timeout 设置默认页面加载时间 driver.set_page_load_timeout(0.8) driver.get("https://www.tutorialspoint.com/index.htm")
使用隐式等待实现代码。
from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\chromedriver.exe") #已应用 0.8 秒的隐式等待 driver.implicitly_wait(0.8) driver.get("https://www.tutorialspoint.com/index.htm")