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
CodePudding user response:
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
CodePudding user response:
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