简体   繁体   中英

Java - Get error when trying to login to a website with selenium webdriver (htmlunit)

I tried the below code with actual credentials for Indeed.com, and I get an error: Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate a node using //*[@id="signin_email"]

I get a similar error when I use By.id instead of By.xpath, any idea what's going on?

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;


public class Testing {

public static void main(String[] args) {

                WebDriver driver = new HtmlUnitDriver();

                driver.get("https://secure.indeed.com/account/login?service=my&hl=en_CA&co=CA");
                driver.findElement(By.xpath("//*[@id=\"signin_email\"]")).sendKeys("notworking@gmail.com");
                driver.findElement(By.xpath("//*[@id=\"signin_password\"]")).sendKeys("needHelp");
                driver.findElement(By.xpath("//*[@id=\"loginform\"]/button")).click();  
                driver.quit(); 

 } 
}

You need to enable java script, see the updated code.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;


public class Testing {

public static void main(String[] args) {

                HtmlUnitDriver driver = new HtmlUnitDriver();
                driver.setJavascriptEnabled(true);
                driver.get("https://secure.indeed.com/account/login?service=my&hl=en_CA&co=CA");
                driver.findElement(By.xpath("//*[@id=\"signin_email\"]")).sendKeys("notworking@gmail.com");
                driver.findElement(By.xpath("//*[@id=\"signin_password\"]")).sendKeys("needHelp");
                driver.findElement(By.xpath("//*[@id=\"loginform\"]/button")).click();  
                driver.quit(); 

 } 
}

The login form is added via JS not regular HTML. I tried to disable JS in the browser and all I could see was:

<div id="container"></div>

This means that all you have to do is:

  • Enable JavaScript for your driver: driver.setJavascriptEnabled(true);

  • Wait until "signin_email" is rendered: driver.until(ExpectedConditions.presenceOfElementLocated(By.id("signin_email")))

The second bullet will give you stable test on different PCs. Sometimes, on weaker machines, the assertions may execute faster than the element was rendered by JS which leads to random failures.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM