如何設定 Selenium Python WebDriver 預設超時時間?
我們可以使用 Selenium webdriver 設定預設超時時間。set_page_load_timeout 方法用於為頁面載入設定超時。等待時間(以秒為單位)作為引數傳遞給該方法。
語法
driver.set_page_load_timeout(5)
如果在等待時間過去後頁面仍未載入,則會丟擲 TimeoutException。
我們可以在同步中使用隱式等待概念來定義預設超時時間。這是一個全域性等待時間,適用於頁面中的每個元素。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 to set the default page load time driver.set_page_load_timeout(0.8) driver.get("https://tutorialspoint.tw/index.htm")
使用隱式等待的程式碼實現。
from selenium import webdriver driver = webdriver.Chrome(executable_path="C:\chromedriver.exe") #implicit wait of 0.8 seconds applied driver.implicitly_wait(0.8) driver.get("https://tutorialspoint.tw/index.htm")
廣告