如何使用selenium通过调试器端口连接到现有的FireFox实例?

问题描述 投票:0回答:1

我想分别启动 Firefox 和 geckodriver,但似乎 selenium 没有导出用于运行 geckodriver 的接口,该接口准备连接到现有的 FireFox 实例。

对于 chromium,我可以使用以下代码来完成此任务:

chromium = subprocess.Popen(
            [self.chromium_path, "--headless", "--no-sandbox",
             "--remote-debugging-port=" + port])
ops = selenium.webdriver.ChromeOptions()
        ops.debugger_address = "127.0.0.1:" + port
browser = selenium.webdriver.Chrome(self.chrome_driver_path, options=ops)

如何以这种方式运行 FireFox?

selenium selenium-webdriver firefox selenium-chromedriver
1个回答
0
投票

首先,以远程可控状态启动Firefox:

  1. 关闭 Firefox 的所有实例

  2. 使用记录很少的 --marionette 命令行开关启动 Firefox:

    “c:\Program Files\Mozilla Firefox irefox.exe”--marionette

Firefox 将启动,除了小机器人图标和地址栏上相当烦人的粉色/灰色条纹外,它将正常运行。

然后从这里下载最新版本的 GeckoDriver 。将其复制到包含 firefox.exe 的同一目录中(Windows 上为 c:\Program Files\Mozilla Firefox\)。毕竟,它是 Firefox 的一部分,应该与 Firefox 一起分发。

然后,在 Selenium Java 中,像这样打开 FirefoxDriver:

import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.GeckoDriverService;

public final class Browser {
    private Browser() {
    }

    private static WebDriver driver = null;

    public static WebDriver open() throws IOException {
        if (driver == null) {
            List<String> args = new ArrayList<>();
            args.add("--port=43068");
            args.add("--allow-origins");
            args.add("http://127.0.0.1:45015");
            args.add("http://localhost:45015");
            args.add("http://[::1]:45015");
            args.add("--marionette-port=2828");
            args.add("--connect-existing");
            var env = new HashMap<String, String>();
            var service = new GeckoDriverService(
                new File("c:\\Program Files\\Mozilla Firefox\\geckodriver.exe"),
                43068,
                Duration.ofSeconds(20),
                args,
                env
            );
            driver = new FirefoxDriver(service);
        }
        return driver;
    }
    ...

不幸的是,你不能使用 GeckoDriverService.Builder,因为 createArgs() 在那里是硬编码的,它无法将最重要的“--connect-existing”参数插入到参数列表中。

对于示例中的硬编码神奇端口号,我感到很抱歉。稍后我将重写 GeckoDriverService.Builder,并制定适当的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.