-2

Can someone help me fixing NoSuchElementException. Let me explain what I am trying to do.

I am trying to login into an application with multiple sets of data. Lets say,

1) Valid username and password.

2) Valid username and invalid password

Iam Data driven Testing poi my Excel in three Colums (user ,password,Status) and data set Valid username and password. & Valid username and invalid password 2 different rows .

n my first case, element is present as user successfully loggedIn(passed ). But in my second case, user is logged in and i am trying to find element present failed (NoSuchElementException)

Can any one tell me how to find a solution for such situation ?

My Code is :

   package functionalTTM;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

//import Demo1.ExcelOperation;
//import Demo1.ValidationOperation;

public class Demo  {


WebDriver driver;

HSSFWorkbook workbook;
HSSFSheet sheet;
HSSFCell cell;
@BeforeTest
public void TestSetup(){
 SSystem.setProperty("webdriver.chrome.driver","C:\\chrome\\chromedriver.exe");
driver = new ChromeDriver();
 driver.get("http://www.gcrit.com/build3/login.php");
 //driver.manage().window().maximize();
  driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
@Test
public void ReadData() throws IOException, Exception{ 
File src=new File("D:\\Book3.xls");   


FileInputStream fis = new FileInputStream(src);
workbook = new HSSFWorkbook(fis);
sheet= workbook.getSheet("Sheet1");                   
for(int i=1; i<=sheet.getLastRowNum(); i++){
cell  = sheet.getRow(i).getCell(0);
cell.setCellType(CellType.STRING);
driver.findElement(By.xpath("//input[@name='email_address']")).sendKeys(cell.getStringCellValue());
cell = sheet.getRow(i).getCell(1);
cell.setCellType(CellType.STRING);
 driver.findElement(By.xpath("//input[@name='password']")).sendKeys(cell.getStringCellValue());
  Thread.sleep(500);
  cell = sheet.getRow(i).getCell(2);
  cell.setCellType(CellType.STRING);
  driver.findElement(By.xpath("//*[@id='tdb5']/span[2]")).click();
  String ExpectedResult=cell.getStringCellValue();
  String ActualResult=driver.getCurrentUrl();
 System.out.println(ActualResult);
 sheet.getRow(i).createCell(3).setCellValue(ActualResult);
FileOutputStream fos=new FileOutputStream(src);
String status=ValidationOperation.verify(ExpectedResult, ActualResult);
sheet.getRow(i).createCell(4).setCellValue(status);
workbook.write(fos);
 WebElement link_Home =driver.findElement(By.xpath("//*[@id='tdb4']/span"));
      Actions action2 = new Actions(driver);
     action2.moveToElement(link_Home).build().perform();
     Thread.sleep(500);
driver.findElement(By.xpath("//*[@id='tdb4']/span")).click();
driver.navigate().to("http://www.gcrit.com/build3/login.php");
  Thread.sleep(500);
fos.close();
}

}  


public static class ValidationOperation {

    public static String verify(String ExpectedResult,String ActualResult) {

        try
        {
            Assert.assertEquals(ExpectedResult, ActualResult);
            return "pass";
        }
        catch(AssertionError rv)
        {
            return "fail";


        }


}   }
}  

Note : Can you please help me for loop failed invalid dataset . How to handle this type of problems

Errror :

[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output\Default suite exists: true
FAILED: ReadData
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//span[text()='Log Off']"}
  (Session info: chrome=74.0.3729.131)
  (Driver info: chromedriver=2.44.609538 (b655c5a60b0b544917107a59d4153d4bf78e1b90),platform=Windows NT 10.0.17134 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/no_such_element.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:25:53'
System info: host: 'DESKTOP-90QO8AJ', ip: '192.168.0.104', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_191'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.44.609538 (b655c5a60b0b54..., userDataDir: C:\Users\A7710~1\AppData\Lo...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:54786}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: ignore, unhandledPromptBehavior: ignore, version: 74.0.3729.131, webStorageEnabled: true}
Session ID: e724288247f09f8379f951ca90005e92
*** Element info: {Using=xpath, value=//span[text()='Log Off']}
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
    at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:80)
    at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:44)
    at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:323)
    at org.openqa.selenium.remote.RemoteWebDriver.findElementByXPath(RemoteWebDriver.java:428)
    at org.openqa.selenium.By$ByXPath.findElement(By.java:353)
    at org.openqa.selenium.remote.RemoteWebDriver.findElement(RemoteWebDriver.java:315)
    at naresh.Demo.ReadData(Demo.java:78)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:100)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:646)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:811)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1137)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
    at org.testng.TestRunner.privateRun(TestRunner.java:753)
    at org.testng.TestRunner.run(TestRunner.java:607)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:368)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:363)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:321)
    at org.testng.SuiteRunner.run(SuiteRunner.java:270)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1284)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1209)
    at org.testng.TestNG.runSuites(TestNG.java:1124)
    at org.testng.TestNG.run(TestNG.java:1096)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)


===============================================
    Default test
    Tests run: 1, Failures: 1, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================

[TestNG] Time taken by org.testng.reporters.jq.Main@6e8dacdf: 643 ms
[Utils] Attempting to create C:\Users\A77 10\eclipse-workspace\Selenium\test-output\testng-failed.xml
[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output exists: true
[Utils] Attempting to create C:\Users\A77 10\eclipse-workspace\Selenium\test-output\Default suite\testng-failed.xml
[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output\Default suite exists: true
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 58 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@7e0ea639: 349 ms
[Utils] Attempting to create C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite\toc.html
[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite\Default test.properties
[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite\index.html
[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite\main.html
[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite\groups.html
[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite\classes.html
[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite\reporter-output.html
[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite\methods-not-run.html
[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite\testng.xml.html
[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old\index.html
[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output\old exists: true
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@6a5fc7f7: 566 ms
[Utils] Attempting to create C:\Users\A77 10\eclipse-workspace\Selenium\test-output\junitreports\TEST-naresh.Demo.xml
[Utils]   Directory C:\Users\A77 10\eclipse-workspace\Selenium\test-output\junitreports exists: true
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@7a0ac6e3: 325 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@5b464ce8: 116 ms

marked as duplicate by c32hedge, Nitin Rastogi, Bharat Mane, Kevin McKenzie, NarendraC May 17 at 13:08

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • where is your this Xpath - //span[text()='Log Off']. – Upkar Singh May 2 at 9:39
2

If I understand correctly - You want to check if some particular WebElement is missing. While doing so you get a NoSuchElementException.

The solution here will be to create a function that returns a boolean value if an element is present. Something like this:

public boolean isPresent(By locator) {
    try {
        webDriver.findElement(locator);
        return true;
    } catch (NoSuchElementException e) {
        return false;
    }
}
  • Is there any graceful way to trust this sort of function in the face of variable load speeds? - ie, calling isPresent(x) just before x has actually been loaded? – TheLuckless May 2 at 17:16
  • 1
    It acts the same way as findElement() the only difference is that we handle the exception here. The other aproach is to look for a List of WebElements using findElements instead and check if the size is > 0. Of course this can also be extended with some FluentWait's and so on. I just gave the most basic example. – Moro May 2 at 19:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.