How to make driver quit if it can't find element in 2 seconds

Question:

How to make web driver quit after 2 seconds if it cant find the element in that particular time .

Is there any way set timeout for driver if it cant find an element.

Asked By: user11669928

||

Answers:

Here I post my code snippet for waiting for an element to be present.
This shows an idea of how to implement such things.
Hope this helps.

    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))
            return False
Answered By: Jalil Markel

Just use explicit selenium wait, after timeout it return TimeoutException that you can catch

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)

This is the imports you need:

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 
Answered By: brfh