how to check whether the element exists or not in pages

Viewed 44

My work is use selenium.webdriver class to click the button in pages with python. If I am trying to find a element in page by xpath,sometimes the element may not exist.So before i use the element I should check whether the element exists or not. The most popular way to solve this question is to use try...expect statement. like this

    def ElementExists(xpath):
   try:
      driver.find_element("xpath",xpath)
      return True
   except:
      return False

It works well. But i find the time cost in try...expect statement is so long. It will cost almost 15 seconds, so what can we do to reduce the time cost with another way? Thanks

3 Answers

A potentially faster alternative would get rid of the try and catch construction:

def ElementExists(xpath):
    e = driver.find_element_by_xpath('xpath')
    if e:
        return True
    return False

Instead of driver.find_element with try-except block you can simply use driver.find_elements method.
Something like this:

def ElementExists(xpath):
    driver.find_elements(By.XPATH, your_xpath)

driver.find_elements will return you a list of web elements matching the passed locator. In case such elements found it will return non-empty list interpreted by Python as a Boolean True while if no matches found it will give you an empty list interpreted by Python as a Boolean False

In my limited experience with the work, I find driver.find_elements is a good way to check the elements.Also we can use css_selector to improve the performance.

But if I want to reduce the time cost, the bottleneck of code performance is the parameter settings of the implicit_waits

driver.implicitly_wait(10)

implicit_wait tells WebDriver to poll the DOM for a certain amount of time when trying to find any element (or elements) not immediately available.

This means that every time you look for an element that doesn't exist, it waits 10 seconds. Reducing the time to 2-3 seconds will improve the runtime.

like this:

driver.implicitly_wait(2)

Thanks to above answering for my question, it is inspiring for my exploration of the result.

Related