If you use an element that does not exist in Selenium, you will get a Message: Unable to locate element: xxx error. I want to check the existence of the element in advance.
Occasionally, I see a method of handling exceptions with the following try, but in fact it can also be judged with len.
try:
driver.find_element_by_id('test').click()
except:
#not exist
The point is to use driver.find_elements_by_id instead of driver.find_element_by_id. At first glance, it looks the same, but in the former case, an abnormality occurs when the element does not exist. In the latter case, the anomaly does not occur even if the element does not exist. Specifically, it is used as follows.
if len(driver.find_elements_by_id('test') > 0) :
ele = driver.find_element_by_id('test')
#Processing when it exists
else:
#Processing when it does not exist
Recommended Posts