2

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 1

12

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

Sign up to request clarification or add additional context in comments.

10 Comments

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
My answer includes what you asking for. What do you want to do in case the element existing and what in other case?
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?
try: check = web.find_element(By.CLASS_NAME, "zip_code_address unused-hide") print ("Yes") except: print ("Not")
This keeps evaluating to not for some reason
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.