I want to just check if an element is there or not within a for loop but it just throws an exception and ends the code. How do I go about this?
1 Answer
Instead of driver.find_element you should use driver.find_elements method here.
Something like this:
if driver.find_elements_by_xpath("/div[@class='class_name']"):
driver.find_element_by_xpath("/div[@class='class_name']").click()
Or this:
elements = driver.find_elements_by_xpath("/div[@class='class_name']")
if elements:
elements[0].click()
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
10 Comments
Hocian Wade
Thanks this was helpful, but I'm using it in a for loop. How would you go about writing an if else/elif for the element not existing? like a boolean kind of answer. It keeps saying the wrong one
Prophet
My answer includes what you asking for. What do you want to do in case the element existing and what in other case?
Hocian Wade
I just want a simple yes or no, but it keeps telling me either yes all the time or no all the time, like its not really checking anything. How do I like store it as a boolean value in a way or something like that?
Hocian Wade
try: check = web.find_element(By.CLASS_NAME, "zip_code_address unused-hide") print ("Yes") except: print ("Not")
Hocian Wade
This keeps evaluating to not for some reason
|