Search code examples
pythonseleniumselenium-webdriverautomationselenium-rc

Selenium check if element exists without exception


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?


Solution

  • 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