这是我启动 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/