Selenium 支持无头浏览器测试吗?

seleniumautomation testingtesting tools更新于 2026/2/5 7:07:17

是的,Selenium 支持无头浏览器测试。这可以通过 HTMLUnitDriver 来实现。它是所有浏览器驱动程序中速度最快的 Web 驱动程序,并且与平台无关。

Selenium 2.53 版本之后,必须在项目中明确添加 HTMLUnitDriver jar。要添加依赖项,请按照以下步骤操作 −

  • 右键单击项目并选择构建路径。然后点击配置构建路径。

  • 前往Java 构建路径,然后选择库。点击添加外部 JAR。然后浏览并添加 HTMLUnitDriver jar。

  • 我们必须将 org.openqa.selenium.htmlunit.HtmlUnitDriver 添加到项目中。

示例

代码实现。

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class HeadlessMode{
   public static void main(String[] args) {
      //HtmlUnitDriver 初始化
      HtmlUnitDriver driver = new HtmlUnitDriver();
      driver.get("https://www.tutorialspoint.com/questions/index.php");
      // 等待 5 秒
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      System.out.println("Page title: " + driver.getTitle());
   }
}

输出

此外,执行过程中不会显示任何浏览器。


相关文章