【问题标题】:How to execute else if(xpathcondition) , If first xpathcondition fails?如果第一个 xpathcondition 失败,如何执行 else if(xpathcondition) ?
【发布时间】:2015-04-09 12:30:58
【问题描述】:
if(driver.findElement(By.xpath("//div/h3[contains(text(),'MOVENPICK HOTEL DEIRA')]")).isDisplayed())
{
}
else if(driver.findElement(By.xpath("//div/h3[contains(text(),'HOTEL INN')]")).isDisplayed())
{
}

在上面的代码中,如果条件失败意味着如何执行else if(xpathcondition), 对于失败的情况,其将异常显示为“未找到元素”。如果我处理了异常,else if如何执行? 提前感谢您的帮助!!

【问题讨论】:

    标签: java selenium xpath selenium-webdriver


    【解决方案1】:

    理想情况下,isDisplayed() 应该返回 false 而不是抛出异常。

    你可以用 saifur 回答。另一种方法是(根据this

    try {
    
     if(driver.findElement(By.xpath("//div/h3[contains(text(),'MOVENPICK HOTEL DEIRA')]")).isDisplayed())
        {  }
    
    }catch(){  //catch executes the else part when the exception is thrown.
    
        if(driver.findElement(By.xpath("//div/h3[contains(text(),'HOTEL INN')]")).isDisplayed())
        {    }
    
    }
    

    也检查一下issue

    【讨论】:

      【解决方案2】:

      这里的问题是,如果任何元素查找失败,测试将因 NoSuchElementElement not Found 异常而终止,因为元素不是 dom 的一部分.为避免这种情况,您可以稍微欺骗代码或再次检查元素是否存在。

      我宁愿找到元素并匹配文本并执行其他任务

      // Write a selector that would meet the find both elements
      WebElement element = driver.findElement(By.cssSelector("div h3"));
      
      if (element.getText().contains("MOVENPICK HOTEL DEIRA")) {
          //do this
      } else if (element.getText().contains("HOTEL INN")) {
          //do something
      } else {
          //do nothing and log some error
      }
      

      【讨论】:

      • 感谢您的回答。但是对于我来说,这个问题发生了,如果(条件)失败,它没有直接执行(否则如果)它执行第三个其他部分,对此有任何想法。
      • 嘿,我认为需要借助 driver.findElements 将 WebElement 存储在动态数组中。在这种情况下,其他部分已被执行。谢谢你的想法!!
      • 请提供您正在处理的 html,我会知道为什么会这样。特别是我想知道这些元素中的任何一个是否变得不可见或完全消失。
      • 您好,您可以查看以下网站,点击酒店部分并提供城市为“迪拜”,重定向到搜索结果后选择任意三间酒店。你能提供样品吗,网址:holidaysonclick.com
      • 能否详细描述一下这个问题。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-17
      • 2016-01-24
      • 2020-01-24
      相关资源
      最近更新 更多