java - IllegalStateException : Unable to locate element by name for com. gargoylesoftware.htmlunit.UnexpectedPage 与 HtmlUnitDriver 而 getTitle()

标签 java selenium selenium-webdriver headless-browser htmlunit-driver

这是我启动 HTMLUnit 浏览器并获取标题的基本代码。运行代码时,我得到的标题为空,后来它抛出以下执行:

使用的 jar :

  • htmlunit-driver-2.33.0-jar-with-dependency.jar
  • selenium-server-standalone-3.14.0.jar

代码试验:

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

public class HtmlUnitDriverTest {

    public static void main(String[] args) throws InterruptedException {

        WebDriver driver = new HtmlUnitDriver();
        Thread.sleep(5000);
        driver.get("https://google.com");
        System.out.println(driver.getTitle());

        driver.findElement(By.name("q")).sendKeys("testing");

    }

}

输出:

Exception in thread "main" java.lang.IllegalStateException: Unable to locate element by name for com.gargoylesoftware.htmlunit.UnexpectedPage@2e32ccc5

at org.openqa.selenium.htmlunit.HtmlUnitDriver.findElementByName(HtmlUnitDriver.java:1285)

最佳答案

您需要考虑几个事实:

  • 在调用 HtmlUnitDriver() 之后立即引入 Thread.sleep(5000); 实际上没有任何意义。您可以在调用 driver.get() 后使用 Thread.sleep(5000);。然而,根据最佳实践,硬编码Thread.sleep(n)隐式等待应替换为WebDriverWait>.

  • 在这里您可以找到关于 Replace implicit wait with explicit wait (selenium webdriver & java) 的详细讨论

  • 您看到标题null,因为驱动程序甚至在之前尝试提取页面标题页面标题HTML DOM内呈现

  • 作为使用 htmlunit-driver-2.33.0-jar-with-dependency.jar 的解决方案,您需要为 Page 引入 WebDriverWait标题在提取之前包含字符序列,您可以使用以下解决方案:

  • 代码块:

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.htmlunit.HtmlUnitDriver;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    public class A_HtmlunitDriver_2_33_0 {
    
        public static void main(String[] args) throws InterruptedException {
    
            WebDriver driver = new HtmlUnitDriver();
            driver.get("https://google.com");
            new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("Go"));
            System.out.println(driver.getTitle());
        }
    }
    
  • 控制台输出:

    Google
    

关于java - IllegalStateException : Unable to locate element by name for com. gargoylesoftware.htmlunit.UnexpectedPage 与 HtmlUnitDriver 而 getTitle(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53044022/

相关文章:

java - 使用 am 实用程序在 Android 方法分析中缺少方法

java - TestNG 测试使用一个测试的参数而不是自己的参数

c# - ExecuteScript(setInterval) 完成后继续 `while` 循环

java - 使用 Spray 访问 GAE 数据存储

java - 使用 JDBC 时,Oracle 在 Postgresql 中的 REF CURSOR 等效于什么?

java - 从alertDialog内的onClickListener访问全局变量

javascript - 我无法编辑 Selenium Standalone 上的超时

java - 如何确定 WebElement 是否存在于 Selenium 中?

java - 线程 "main"org.openqa.selenium.WebDriverException 中出现异常

PHPUnit_Extensions_Selenium2TestCase 与 PHPUnit_Extensions_SeleniumTestCase ?我很困惑该使用哪一个