![](/img/trans.png)
[英]C# Changing the existing Firefox Profile location in selenium webdriver
[英]Can't use existing Firefox profile in Selenium WebDriver using C#
我需要为 Firefox 使用共享配置文件,该配置文件在退出时不会被删除。 似乎这可以使用FirefoxProfile
或FirefoxOptions
来完成。 但它们似乎都不起作用:启动 geckodriver 时,它使用这样的临时配置文件
1507646897935 mozrunner::runner INFO 运行命令:“C:\\Program Files\\Mozilla Firefox\\firefox.exe”“-marionette”“-profile”“C:\\Users\\\\AppData\\Local\\Temp\\rust_mozprofile.uzI9KAmLQ1zP”
在调试时,我注意到配置文件的属性ProfileDirectory
始终为 null。
var profileManager = new FirefoxProfileManager();
var profile = profileManager.GetProfile("Test");
var driver = new FirefoxDriver(profile);
配置文件Test 之前是使用firefox -p
手动创建的。 我也尝试使用它的位置是这样的:
var profile = new FirefoxProfile(@"C:\Users\<MyUsername>\TestProfile", deleteSourceOnClean: false);
但同样的问题,无法弄清楚为什么这不起作用。
通过将我的配置文件的路径作为常规 CLI 参数传递给 Chrome 解决了这个问题:
var options = new ChromeOptions();
options.AddArgument(@"--user-data-dir=C:\Users\<MyUsername>\TestProfile");
var driver = new ChromeDriver(options);
也应该与 Firefox 一起使用。 但我需要切换到 Chrome,直到 FF 驱动程序中的另一个错误得到修复。 这根本不是完全干净的解决方案,但它可以作为一种解决方法,直到找到更好的解决方案。
在 Firefox 中,我需要保留所有 cookie、历史记录、缓存等,但没有任何效果,因为 selenium 不是为了在会话中保存任何这些而构建的,原因很明显。
由于没有针对 Firefox 的解决方案,以下是我如何破解它
这是代码:
IWebDriver _driver;
var service = FirefoxDriverService.CreateDefaultService();
//Start webdriver
_driver = new FirefoxDriver(service, options);
//get the webdriver commandline so we can get the path of the ff profile temp dir so we can save it later
var proc = service.ProcessId;
string cmdline = GetCommandLine(proc);
string profilePath = cmdline.Substring(cmdline.IndexOf(" -profile ") + 10);
//Do stuff with your browser
//In order to move the temp profile dir, we have to 'manually' close the browser window.
//There is no other way because the temp profile gets deleted if you use _driver.close()
var ffprocess = Process.GetProcesses().FirstOrDefault(x => x.MainWindowTitle == $"{title} - Mozilla Firefox");
ffprocess.CloseMainWindow();
//Delete the old profile data so we can get the updated data.
Directory.Delete(sProfile, true);
//store the temp profile data
Directory.Move(profilePath, sProfile);
//this must be deleted, othervise the webdriver won't start next time
File.Delete(sProfile + @"\user.js");
string GetCommandLine(int process)
{
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher($"SELECT CommandLine FROM Win32_Process WHERE CommandLine Like \"% -profile %\" AND ParentProcessID = {process}"))
using (ManagementObjectCollection objects = searcher.Get())
{
return objects.Cast<ManagementBaseObject>().SingleOrDefault()?["CommandLine"]?.ToString();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.