Skip to content Skip to sidebar Skip to footer

Selenium: Error Comes Using "if" To Decide Whether An Element Exists Or Not

I am sorry that if I ask a duplicate/stupid questions. I am confused with how to decide if an element exists. Errors:'Could not locate the id 'smc'' will pop up if you run the foll

Solution 1:

You wrote the solution itself in your question. WebDriver throws NoSuchElementException if it is not able to find the element with the given locator and you need to handle it using try-except if you want your code to go to to an alternate path.

Other option you can use, if you don't want to handle exceptions is driver.find_elements. It returns a list of elements matching a locator and an empty list if it couldn't find any. So you will do something like -

count = len(driver.find_elements_by_id('some_id'))
if count == 0:
   //element was not found.. do something else instead

Solution 2:

Try to replace

if driver.find_element_by_id("smc")

with

if driver.find_elements_by_id("smc")

Solution 3:

As per your question to decide the three options and run the next step accordinglyyou can use the following solution :

  • You can write a function as test_me() which will take an argument as the id of the element and provide the status as follows:

    def test_me(myString):
        try:
            driver.find_element_by_id(myString)
            print("Exits")
        except NoSuchElementException:
            print("Doesn't exit")
    
  • Now you can call the function test_me() from anywhere within your code as follows:

    test_me("smc")
    #or
    test_me("editPage")
    #
    test_me("cas2_ilecell")
    

Solution 4:

You can write you own method to check if element exists, Java example:

public boolean isExist(WebDriver driver, By locator) {
    try {
        return driver.findElement(locator) != null;
    } catch (WebDriverException | ElementNotFound elementNotFound) {
        return false;
    }
}

In python maybe it will look like(not sure!) this:

def isExist(driver, by, locator):
    try:
        return driver.find_element(by, locator) is None
    except NoSuchElementException:
        return False

Or

def isExist(driver, id):
    try:
        return driver.find_element_by_id(locator) is None
    except NoSuchElementException:
        return False

and use it:

if isExist(driver, "smc")
   fun1()

Post a Comment for "Selenium: Error Comes Using "if" To Decide Whether An Element Exists Or Not"