如何使用 Selenium 以无头模式连接到 Chromium?

seleniumautomation testingtesting tools

我们可以使用 Selenium 以无头模式连接到 Chromium。无头执行有助于降低资源利用率,是业界常用的一项现代技术。

Chrome 59 版本之后支持无头模式。ChromeOptions 类用于更改默认浏览器行为。headless 值作为无头执行的参数传递给 addArguments 方法。

语法

ChromeOptions op = new ChromeOptions();
op.addArguments("headless");
WebDriver d = new ChromeDriver(op);

示例

代码实现。

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.util.concurrent.TimeUnit;
public class HeadlessChromium{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      //ChromeOptions 对象
      ChromeOptions op = new ChromeOptions();
      //无头参数
      op.addArguments("headless");
      // 将 options 参数配置到 Chrome 驱动程序
      WebDriver driver = new ChromeDriver(op);
      driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/about/about_careers.htm");
      // 获取页面标题
      System.out.println("Page title in headless mode: " + driver.getTitle());
   }
}

输出


相关文章