0

I am doing automation and making my code dynamic, in that way either element found or not, app should run smoothly and flawlessly. Right now, problem is there is an alert message which appears occasionally. let us say its A. It appears some time and some time not. Now I am using

A= driver.find_element_by_xpath("abc")
    if A.isdisplay():
            (whatevery my function is)
    else:
         (Do this)

but sometimes A does not appears, in that way script throws an exception and test got failed. Can someone please help me on this?

TeSter
  • 119
  • 1
  • 11

1 Answers1

2

One way is to use find_elements_by_xpath instead (notice the s), which returns an array of found elements or an empty list if none exist. So you could use it like this:

elements = driver.find_elements_by_xpath("abc")

if elements and elements[0].is_displayed():
    # (whatevery your function is)
else:
    # (Do this)


Another way is to use a try/catch statement, like this for example:

from selenium.common.exceptions import NoSuchElementException

try:
    A = driver.find_element_by_xpath("abc")
except NoSuchElementException:
    A = None

if A is not None and A.is_displayed():
    # (whatevery your function is)
else:
    # (Do this)
JeffC
  • 22,180
  • 5
  • 32
  • 55
Omar Einea
  • 2,478
  • 7
  • 23
  • 35