如何处理 Python 中 selenium/Appium 中偶尔出现的警报消息

How to deal with occasional alert message in selenium/Appium in Python

我正在执行自动化并使我的代码动态化,这样无论是否找到元素,应用程序都应该 运行 顺利且完美。 现在,问题是偶尔会出现一条警告消息。 让我们说它的A。 有时会出现,有时不会。现在我正在使用

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

但有时 A 不会出现,这样脚本就会抛出异常并且测试失败。 有人可以帮我解决这个问题吗?

一种方法是使用 find_elements_by_xpath 代替(注意 s),其中 returns 一个找到的元素数组或一个空列表,如果 none 存在。所以你可以这样使用它:

elements = driver.find_elements_by_xpath("abc")

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


另一种方法是使用 try/catch 语句,例如:

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)