首页 文章

org.openqa.selenium.NoSuchElementException:无法找到元素

提问于
浏览
2

如果saleIdValueIs正确,但当saleIdValueIs数据不正确时,此代码工作正常 . 然后它显示一条错误消息“org.openqa.selenium.NoSuchElementException:无法找到元素”

driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
        driver.findElement(By.xpath("//html/body/div/div/div[2]/div[2]/div/div/div/div/div/div/div/div/div[2]/div/div/div/div/div/fieldset/div/div/div/div[2]/div[2]/input")).sendKeys(saleIdValueIs);
        search_transaction_bt.click();
        boolean saleIdVisible=driver.findElementByXPath("/html/body/div/div/div[2]/div[2]/div/div/div/div/div/div/div/div/div/div/div").isDisplayed();
        String searchedSaleIdValue=saleIdValue.getText();
        System.out.println(saleIdVisible);
            if (saleIdVisible==true){
                    System.out.println("sale id  is  - "+saleIdValueIs+ "output is "+searchedSaleIdValue);
                    }       
                else{
                     System.out.println("error message is coming ");
                    boolean errorMessageDisplayTest= driver.findElement(By.xpath("/html/body/div[2]/div/div")).isDisplayed();
                    System.out.println(errorMessageDisplayTest);
                    boolean errorMessageVisible= driver.findElement(By.xpath("/html/body/div[2]/div/div")).isDisplayed();
                    System.out.println(errorMessageVisible);
                    driver.close();
                    }

1 回答

  • 3

    你得到那个错误因为元素
    driver.findElementByXPath("/html/body/div/div/div[2]/div[2]/div/div/div/div/div/div/div/div/div/div/div") 未显示,
    因此,请使用 isElementPresent 而不是 isDisplayed . 下面是代码,如有任何疑问,请与我联系

    boolean saleIdVisible= isElementPresent(By.xpath("/html/body/div/div/div[2]/div[2]/div/div/div/div/div/div/div/div/div/div/div"), driver);
    if(Present)
    {
    System.out.println("sale id  is  - "+saleIdValueIs+ "output is "+searchedSaleIdValue);
     else{
    System.out.println("error message is coming ");
    boolean errorMessageDisplayTest= driver.findElement(By.xpath("/html/body/div[2]/div/div")).isDisplayed();
    System.out.println(errorMessageDisplayTest);
    boolean errorMessageVisible= driver.findElement(By.xpath("/html/body/div[2]/div/div")).isDisplayed();
    System.out.println(errorMessageVisible);
    driver.close();
    }
    
    
    public static boolean isElementPresent(By by, WebDriver driver) 
        {
          boolean present;
          try
            {
              driver.findElement(by);
              present = true;
            }catch (NoSuchElementException e)
            {
              present = false;
             }
         return present;
        }
    

相关问题