Java - 尝试使用 selenium webdriver (htmlunit) 登录网站时出错

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

我使用 Indeed.com 的实际凭据尝试了以下代码, 我得到一个错误: 线程 "main" org.openqa.selenium.NoSuchElementException 中的异常:无法使用 //*[@id="signin_email"]

定位节点

当我使用 By.id 而不是 By.xpath 时,我遇到了类似的错误,知道发生了什么吗?

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(); 

 } 
}

您需要启用 java 脚本,查看更新后的代码。

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(); 

 } 
}

登录表单是通过 JS 添加的,不是常规的 HTML。我试图在浏览器中禁用 JS,但我只能看到:

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

这意味着您所要做的就是:

  • 为您的驱动程序启用 JavaScript:driver.setJavascriptEnabled(true);

  • 等到"signin_email"被渲染:driver.until(ExpectedConditions.presenceOfElementLocated(By.id("signin_email")))

第二个子弹会给你在不同的电脑上稳定的测试。有时,在较弱的机器上,断言的执行速度可能比 JS 渲染元素的速度更快,这会导致随机失败。