You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Selenium设置Firefox代理为自动检测的实现方法

解决Firefox代理自动检测模式的设置问题

首先,你需要调整Firefox配置文件中的代理类型参数——Firefox的自动检测代理设置对应的network.proxy.type值是4(你当前设置的2是系统代理模式,这正是你要替换的默认行为)。

下面是修改后的完整代码示例,我帮你补全了缺失的部分:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class SodirRejestracja {
    String baseUrl = "http://google.pl";
    String driverPath = "C:\\geckodriver.exe";
    WebDriver driver;

    @BeforeTest
    public void beforeTest() {
        // 创建Firefox配置文件实例
        FirefoxProfile profile = new FirefoxProfile();
        // 切换为自动检测代理模式(对应浏览器的"自动检测代理设置"选项)
        profile.setPreference("network.proxy.type", 4);
        // 可选:显式开启WPAD自动发现协议(自动检测的底层机制,默认已开启,显式设置避免环境差异)
        profile.setPreference("network.proxy.wpad.enabled", true);

        // 指定GeckoDriver路径
        System.setProperty("webdriver.gecko.driver", driverPath);
        // 将配置好的profile传入FirefoxDriver,让设置生效
        driver = new FirefoxDriver(profile);
        // 可选:最大化浏览器窗口
        driver.manage().window().maximize();
    }

    @Test
    public void testProxySetting() {
        driver.get(baseUrl);
        // 这里可以添加你的具体测试逻辑
    }
}

关键细节说明:

  • network.proxy.type=4:这是实现自动检测代理的核心配置,直接替代原来的系统代理模式(值为2)。
  • 如果你使用的是Selenium 4.x及以上版本,FirefoxProfile已被标记为过时,推荐使用更现代的FirefoxOptions来配置,代码示例如下:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

public class SodirRejestracja {
    String baseUrl = "http://google.pl";
    String driverPath = "C:\\geckodriver.exe";
    WebDriver driver;

    @BeforeTest
    public void beforeTest() {
        FirefoxOptions options = new FirefoxOptions();
        // 配置自动检测代理
        options.addPreference("network.proxy.type", 4);
        options.addPreference("network.proxy.wpad.enabled", true);

        System.setProperty("webdriver.gecko.driver", driverPath);
        driver = new FirefoxDriver(options);
        driver.manage().window().maximize();
    }

    @Test
    public void testProxySetting() {
        driver.get(baseUrl);
        // 测试逻辑
    }
}

为什么推荐FirefoxOptions?

从Selenium 3.x后期开始,FirefoxProfile逐步被FirefoxOptions取代,后者是更统一、更适配新版本Firefox的配置方式,支持更多浏览器新特性,兼容性更好。

内容的提问来源于stack exchange,提问作者mtmx

火山引擎 最新活动