selenium 两个 xpath 测试合二为一

问题描述

我尝试结合检查两种情况:

I try to combine check for two scenarios:

如果启动检查失败,我们会得到一个重试按钮:

If startupcheck fails we get a try again button:

el = WebDriverWait(self.driver, 10).until(
  EC.element_to_be_clickable((By.NAME, "Try again")))

或者 startupcheck 成功我们在一个自定义对象中得到一个 pin 输入请求:

Or startupcheck succeed we get a pin enter request in a custom object:

el = WebDriverWait(self.driver, 20).until(
  EC.element_to_be_clickable((By.XPATH, "//Custom/Edit")))

如何将其合并为一项检查而不必同时检查两者:我尝试了以下方法:

How can this be combined into one check without having to check for both: I tried the following:

check = WebDriverWait(self.driver, 20).until(
  EC.element_to_be_clickable(
    (By.XPATH, "//Custom/Edit") or (By.NAME, "Try again")
))

但只检查第一个 or 语句.

But only the first or statement is checked.


解决方案

您可以通过 lambda 表达式使用 OR 子句对两个元素进行组合检查,如下所示:

You can club up combine check for both the elements using OR clause through a lambda expression as follows:

el = WebDriverWait(driver, 20).until(lambda x: (x.find_element_by_name("Try again"), x.find_element_by_xpath("//Custom/Edit")))

另一种解决方案是:

el = WebDriverWait(driver,20).until(lambda driver: driver.find_element(By.NAME,"Try again") and driver.find_element(By.XPATH,"//Custom/Edit"))


作为替代方案,您可以使用等效的 css-selectors 如下:

el = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "[name='Try again'], Custom>Edit")))


参考文献

  • Python/Selenium:WebDriverWait 中的逻辑运算符预期条件
  • 如何通过getText()从html内的多个子节点中提取动态文本

相关文章