1

I am trying to use the PhantomJSDriver. The code below works with FirefoxDriver but will not work with PhantomJSDriver. The error is:

[ERROR - 2016-02-12T16:02:47.717Z] WebElementLocator - _handleLocateCommand - Element(s) NOT Found: GAVE UP. Search Stop Time: 1455292967683 org.openqa.selenium.NoSuchElementException: Error Message => 'Unable to find element with id 'email''

Is there any clear guides on how to do this in Java, or can anyone get this working to login? I'm struggling to find some clarity on this topic.

I'm assuming the error is something to do with the browser being headless which therefore messes up with the paths but I have seen others using similar code and it works for them.

WebDriver driver = new PhantomJSDriver();
try {
    System.out.println("Logging in to Facebook...");

    driver.get("https://www.facebook.com/login");
    System.out.println(driver.getTitle());

    driver.findElement(By.id("email")).sendKeys("USERNAME");
    driver.findElement(By.id("pass")).sendKeys("PASS");
    driver.findElement(By.id("loginbutton")).click();
}
catch (Exception e) {
    e.printStackTrace();
}
Andrew Regan
  • 5,087
  • 6
  • 37
  • 73

1 Answers1

0

There's hundreds of similar questions to this one, e.g. this one. It's an issue that applies more or less equally to all browsers, and is a major cause of test instability.

Basically you're asking the Driver to find id="email" almost immediately (within milliseconds) after the page has been requested, and almost certainly before it has finished loading or that web element has been created in the DOM.

The solution is to wait until the element is ready before trying to send keys to it. See these examples. E.g.

System.out.println(driver.getTitle());

WebDriverWait wait = new WebDriverWait(driver, 10);  // 10 secs max wait
wait.until(ExpectedConditions.presenceOfElementLocated( By.id("email") )); 

driver.findElement(By.id("email")).sendKeys("USERNAME");    

Once you know the DOM is loaded, there's no need to wait for the other elements.

Community
  • 1
  • 1
Andrew Regan
  • 5,087
  • 6
  • 37
  • 73