eclipse 下面的If else条件在我的脚本中不起作用

yeotifhr  于 12个月前  发布在  Eclipse
关注(0)|答案(3)|浏览(154)
driver.findElement(By.id("btnSendMailCopy")).click();
Thread.sleep(3000);
if(driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).isDisplayed())
{     
    driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).click();   
    System.out.println("clicked");
}
else if(driver.findElement(By.id("VendorCardHolderName")).isDisplayed())
{  
    Select dropdown = new Select(driver.findElement(By.id("VendorTinCardType")));
    dropdown.selectByVisibleText("VISA");
    driver.findElement(By.id("VendorCardHolderName")).sendKeys("TestName");

如果不使用if else,我可以成功运行脚本,但当我想运行else部分时,它显示错误为
无法定位元素:{“方法”:“xpath”,“选择器”:“/html/body/section[1]/div/article/nav/button[2]"}

p3rjfoxz

p3rjfoxz1#

按照代码,如果第一个元素被显示,那么在if中执行代码,如果第一个元素没有显示,那么在else中执行代码。
现在简单的事情是,如果第一个元素没有显示,那么我们肯定不会收到任何元素异常,对吗?所以我们需要通过try/catch来处理这个问题。

Boolean dd;

try{
 dd = driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).isDisplayed();
}catch(Exception e){
 //you can print as element not displayed
}

then go for if条件

if(dd==true){
  //do something
  }else{
 //do some thing else
 }

谢谢你,穆拉利

f2uvfpb9

f2uvfpb92#

代码如下:

Boolean dd = driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).isDisplayed();

    if(dd==true)
    {     
        driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).click();   
        System.out.println("clicked");
    }
    else{
        System.out.println("Element is not found");
    }

希望对你有帮助:)

6mzjoqzu

6mzjoqzu3#

试试这个

driver.findElement(By.id("btnSendMailCopy")).click();
    Thread.sleep(3000);
    if(driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).size()>0)
    {     
        driver.findElement(By.xpath("/html/body/section[1]/div/article/nav/button[2]")).click();   
        System.out.println("clicked");
    }
    else if(driver.findElements(By.id("VendorCardHolderName")).size()>0)
    {  
        Select dropdown = new Select(driver.findElement(By.id("VendorTinCardType")));
        dropdown.selectByVisibleText("VISA");
        driver.findElement(By.id("VendorCardHolderName")).sendKeys("TestName");
}

由于您在isDisplayed处检查的元素不可用,因此失败。所以要克服这个问题,你必须编写try/catch或我提供的代码。他们应该工作。

相关问题