如果驱动程序在 2 秒内找不到元素,如何让驱动程序退出
How to make driver quit if it can't find element in 2 seconds
如果 web 驱动程序在特定时间内找不到元素,如何让它在 2 秒后退出。
如果驱动程序找不到元素,有没有办法为驱动程序设置超时?
这里是我 post 等待元素出现的代码片段。
这显示了如何实现这些事情的想法。
希望这有帮助。
def wait_present(self, xpath, timeout = 2):
try:
now = time.time()
future = now + timeout
while time.time() < future:
try:
target = self.browser.find_element_by_xpath(xpath)
if target is not None:
return True
except:
pass
return False
except Exception as e:
self.log_error(str(e))(str(e))
return False
只需使用显式 selenium 等待,超时后它 return 您可以捕获的 TimeoutException
try:
item = WebDriverWait(self.driver,5).until(EC.presence_of_element_located((By.XPATH, "your xpath or other selector")))
except Exception as e:
print("time is over")
exit()
print("item was founded : ", item)
这是您需要的导入:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
如果 web 驱动程序在特定时间内找不到元素,如何让它在 2 秒后退出。
如果驱动程序找不到元素,有没有办法为驱动程序设置超时?
这里是我 post 等待元素出现的代码片段。
这显示了如何实现这些事情的想法。
希望这有帮助。
def wait_present(self, xpath, timeout = 2):
try:
now = time.time()
future = now + timeout
while time.time() < future:
try:
target = self.browser.find_element_by_xpath(xpath)
if target is not None:
return True
except:
pass
return False
except Exception as e:
self.log_error(str(e))(str(e))
return False
只需使用显式 selenium 等待,超时后它 return 您可以捕获的 TimeoutException
try:
item = WebDriverWait(self.driver,5).until(EC.presence_of_element_located((By.XPATH, "your xpath or other selector")))
except Exception as e:
print("time is over")
exit()
print("item was founded : ", item)
这是您需要的导入:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC