配合Kameleo使用时Chrome headless无头模式额外参数不生效如何解决
问题根因
Kameleo的浏览器进程在调用await client.StartProfileAsync(profile.Id)时就已经完成启动,你后续给RemoteWebDriver配置ChromeOptions的操作仅用于连接已经运行的浏览器实例,不会修改已启动进程的运行参数,因此你配置的headless等启动参数不会生效。
正确配置方法
所有浏览器启动参数需要在创建Profile的请求构造阶段就传入,Kameleo会在启动浏览器时加载这些参数,修改后的代码如下:
1. 构造Profile时传入启动参数
var requestBody = BuilderForCreateProfile .ForBaseProfile(baseProfileList[baseId].Id) .SetRecommendedDefaults() .SetProxy("http", new Server("zproxy.lum-superproxy.io", 22225, "lum-customer-joshua901-zone-zone2", "5inhblkgrzxj")) .SetLauncher("chrome") // 在此处添加所有Chrome启动参数 .SetExtraOptions(new Dictionary<string, object> { ["args"] = new List<string> { "--window-size=500,783", "disable-infobars", "--incognito", // 原代码拼写错误为incongito,已修正 "--disable-extensions", "disable-gpu", "--headless=new", // 新版Chrome无头模式,兼容性和一致性更好 "--ignore-certificate-errors", "no-sandbox", "--silent-launch", "--no-startup-window", "--disable-blink-features=AutomationControlled" // 替代原AddExcludedArgument("enable-automation")的效果 } }) .Build();
2. 简化WebDriver连接逻辑
启动浏览器后仅需保留必要的连接参数即可,无需重复传入启动参数:
// 启动浏览器,此时已经加载了所有配置的启动参数 await client.StartProfileAsync(profile.Id); // 连接运行中的浏览器实例 var uri = new Uri($"{KameleoBaseUrl}/webdriver"); var opts = new ChromeOptions(); opts.AddAdditionalOption("kameleo:profileId", profile.Id.ToString()); _driver = new RemoteWebDriver(uri, opts);
补充说明
- 原代码中
--incongito为拼写错误,修正为--incognito后隐身模式才能正常生效 - 推荐使用
--headless=new而非旧版headless参数,Chrome 112+版本的新版无头模式和普通有头模式的行为一致性更高,更难被反爬策略检测
内容的提问来源于stack exchange,提问作者Joshua Harris
相关产品推荐
相关产品推荐

