Selenium C# 中的无头 Firefox

Headless Firefox in Selenium C#

我想运行 firefox headless.

不隐藏浏览器 window 或在虚拟桌面中打开它,Firefox 通过使用“-headless”标志支持无头模式。

问题是我知道如何在 chrome 中执行此操作,但在 Firefox 中不知道。

我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;

namespace MyApp {
public partial class Form1: Form {
    public Form1() {
        InitializeComponent();
    }

    private void StartBtn_Click(object sender, EventArgs e) {

        IWebDriver driver;
        FirefoxOptions options = new FirefoxOptions();
        options.AddArguments("--headless");
        driver = new FirefoxDriver(options);
    }
}
}

我的 WinForm 应用程序只有一个名为 StartBtn 的按钮。 单击按钮时,Firefox 应该 运行 无头,但它会正常打开 window。


更新 我更新了 firefox 到 56.0.1

现在我得到一个不同的错误:

An unhandled exception of type 'OpenQA.Selenium.WebDriverException' occurred in WebDriver.dll

Additional information: Expected browser binary location, but unable to find binary in default location, no 'moz:firefoxOptions.binary' capability provided, and no binary flag set on the command line

从 Windows 和 Mac OS 的版本 56 开始支持 Firefox 中的 Headless 模式。确保安装了正确的版本。

https://developer.mozilla.org/en-US/Firefox/Headless_mode#Browser_support

使用 Firefox v56.0.1Selenium.WebDriver v3.6.0geckodriver v0.19.0 ( x64) 这对我来说是正确的。

关于错误:

An unhandled exception of type 'OpenQA.Selenium.WebDriverException' occurred in WebDriver.dll

确保您使用的 geckodriver 版本正确。我怀疑您在 x64 机器上使用 x32 构建,获取 x64 构建。

https://github.com/mozilla/geckodriver/releases