Reputation: 1
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:
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)
Upvotes: 0
Views: 795
Reputation: 193208
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
Upvotes: 1