Selenium: Error Comes Using "if" To Decide Whether An Element Exists Or Not
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:
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 theid
of the element and provide the status as follows:deftest_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") #ortest_me("editPage") # test_me("cas2_ilecell")
Solution 4:
You can write you own method to check if element exists, Java example:
publicbooleanisExist(WebDriver driver, By locator) {
try {
return driver.findElement(locator) != null;
} catch (WebDriverException | ElementNotFound elementNotFound) {
returnfalse;
}
}
In python maybe it will look like(not sure!) this:
defisExist(driver, by, locator):
try:
return driver.find_element(by, locator) isNoneexcept NoSuchElementException:
returnFalse
Or
defisExist(driver, id):
try:
return driver.find_element_by_id(locator) isNoneexcept NoSuchElementException:
returnFalse
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"