无法在使用C#的Selenium WebDriver中使用现有的Firefox配置文件

3
我需要使用一个共享的Firefox配置文件,并且在退出后不会被删除。似乎可以使用FirefoxProfileFirefoxOptions来实现这一点。但是它们似乎都不起作用:当启动geckodriver时,它使用了一个类似于以下的临时配置文件:

1507646897935 mozrunner::runner INFO Running command: "C:\Program Files\Mozilla Firefox\firefox.exe" "-marionette" "-profile" "C:\Users\\AppData\Local\Temp\rust_mozprofile.uzI9KAmLQ1zP"


调试时,我注意到配置文件的ProfileDirectory属性总是为空。
var profileManager = new FirefoxProfileManager();
var profile = profileManager.GetProfile("Test");
var driver = new FirefoxDriver(profile);

在此之前,手动使用firefox -p创建了名为Test的配置文件。我还尝试像这样使用它的位置:

var profile = new FirefoxProfile(@"C:\Users\<MyUsername>\TestProfile", deleteSourceOnClean: false);

但是还有同样的问题,无法找出为什么这不起作用。

所使用的软件

  • geckodriver 0.19.0
  • Selenium.Firefox.WebDriver 2.0.0 (NuGet)
  • Selenium.WebDriver 3.6.0 (NuGet)
  • ASP.NET Core 2.0
2个回答

0

通过将我的配置文件路径作为常规CLI参数传递给Chrome,解决了这个问题:

var options = new ChromeOptions();
options.AddArgument(@"--user-data-dir=C:\Users\<MyUsername>\TestProfile");
var driver = new ChromeDriver(options);

应该也可以在Firefox上运行,但在FF驱动程序中修复另一个错误之前,我需要切换到Chrome。这并不是完全清洁的解决方案,但它作为一种解决方法,直到找到更好的解决方案。


0

在Firefox中,我需要保留所有的cookies、历史记录、缓存等等,但是由于Selenium并没有为保存这些数据而设计,所以一切都无法实现。

既然Firefox没有解决方案,那么我就想到了一个办法:

  1. 读取firefox.exe命令行,以找到临时配置文件夹。
  2. 手动关闭浏览器,以便临时配置文件不被删除。
  3. 移动临时配置文件,以保留所有数据。

以下是代码:

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();
    }

}

objects.Cast<ManagementBaseObject>().SingleOrDefault() 给出错误,提示找不到转换。 - Sarveshwar
@SarveshwarPM 将其设置为您想要存储配置文件的位置。 - Milos
@SarveshwarPM Firefox启动了吗? - Milos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接