简体   繁体   中英

IllegalStateException: Unable to locate element by name for com.gargoylesoftware.htmlunit.UnexpectedPage with HtmlUnitDriver while getTitle()

Here is my basic code for launching HTMLUnit browser and getting the title. while running the code i am getting the title as null and later it is throwing the following execpetion:

Jars used:

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

Code trials:

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

    }

}

O/p:

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)

You need to consider a couple of facts:

  • Inducing Thread.sleep(5000); just after invoking the HtmlUnitDriver() actually makes no sense. You could have used the Thread.sleep(5000); after you have invoked driver.get() . However as per best practices hard-coded Thread.sleep(n) and Implicit Waits should be replaced by the WebDriverWait .

  • Here you can find a detailed discussion on Replace implicit wait with explicit wait (selenium webdriver & java)

  • You are seeing the title as null as the driver is trying to extract the Page Title even before the Page Title is rendered within the HTML DOM

  • As a solution using htmlunit-driver-2.33.0-jar-with-dependencies.jar you need to induce WebDriverWait for the Page Title to contain a character sequence before extracting and you can use the following solution:

  • Code Block:

     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()); } } 
  • Console Output:

     Google 

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