【问题标题】:(Selenium - Python) Finding one of two elements in webDriver(Selenium - Python) 在 webDriver 中查找两个元素之一
【发布时间】:2021-09-28 00:58:52
【问题描述】:

在我的应用程序中,我可以预期会出现两个元素(a 或 b)之一。我目前有: el1 = driver.find_element_by_id("a")

但是,我想做类似的事情: el1 = driver.find_element_by_id("a" or "b")

这在硒中可能吗?如果有帮助,我正在 Python 中执行此操作。

【问题讨论】:

    标签: python selenium automation appium


    【解决方案1】:

    简单直接的解决方案:

    try:
        # Look for first element
        el1 = driver.find_element_by_id('a')
    except selenium.common.exceptions.NoSuchElementException:
        # Look for the second if the first does not exist
        el1 = driver.find_element_by_id('b')
    

    【讨论】:

      【解决方案2】:

      在这种情况下你可以使用 xpath :

      el1 = driver.find_element_by_xpath("//*[@id= 'a' or @id = 'b']")
      

      我假设two tags in HTML有两个不同的ids,你可以像上面一样在xpath中写or条件。

      更新:

      请注意任何使用 android 应用程序实现此功能的人,语法是:

      el1 = driver.find_element_by_xpath("/hierarchy/a" or "/hierarchy/b")
      

      【讨论】:

      • 我正在测试一个安卓应用,所以 xpath 看起来更像“/hierarchy/a”。将尝试使用我的 xpath 执行您的建议。
      • 成功了。提醒任何使用 android 应用程序实现此功能的人,语法为:el1 = driver.find_element_by_xpath("/hierarchy/a" or "/hierarchy/b")
      • 我也更新了安卓系统。同时,它有帮助吗?如果有,您能否接受这个答案,以便将来的读者可以使用绿色。如果您想接受这个答案,请随时点击投票按钮旁边的复选标记。非常感谢您抽出时间并对此做出回应。
      • 我说得太早了,el1 = driver.find_element_by_xpath("/hierarchy/a" or "/hierarchy/b") 仅在提供的元素为 a 时才有效。另外,这样的东西是否适用于 id 而不是 xpath?还是硒挑剔?
      • 不,它不适用于 id,id 不支持 AND 或 OR,您可以使用 css 选择器来实现。
      【解决方案3】:

      在纯 Python 中,您可以这样做:

      el1 = driver.find_element_by_id("a") if driver.find_element_by_id("a") else driver.find_element_by_id("b") if driver.find_element_by_id("b") else None
      

      【讨论】:

      • 如果 ab 在 DOM 中不可用,OP 将得到 NoSuchElement 异常
      猜你喜欢
      • 2014-08-13
      • 2014-01-03
      • 2012-12-12
      • 2018-09-01
      • 1970-01-01
      • 2017-09-12
      • 2021-03-31
      • 1970-01-01
      相关资源
      最近更新 更多