不能使用C#在Selify WebDriver中使用现有的Firefox配置文件 [英] Can't use existing Firefox profile in Selenium WebDriver using C#

查看:67
本文介绍了不能使用C#在Selify WebDriver中使用现有的Firefox配置文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Firefox的共享配置文件,它在退出时不会被删除。这似乎可以使用FirefoxProfileFirefoxOptions来完成。但它们似乎都不起作用:在启动gecko驱动程序时,它使用如下所示的临时配置文件

1507646897935 mozrunner::runner信息运行命令: "C:程序文件Mozilla FirefoxFirefox.exe""-marionette" "-配置文件" "C:用户\AppDataLocalTemp UST_mozprofile.uzI9KAmLQ1zP"

调试时注意到配置文件的属性ProfileDirectory始终为空。

var profileManager = new FirefoxProfileManager();
var profile = profileManager.GetProfile("Test");
var driver = new FirefoxDriver(profile);

配置文件测试以前是使用firefox -p手动创建的。我还试着这样使用它的位置:

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

但同样的问题,找不出为什么这不起作用。

使用的软件

  • gecko驱动程序0.19.0
  • Selenium.Firefox.WebDriver 2.0.0(NuGet)
  • Selenium.WebDriver 3.6.0(NuGet)
  • ASP.NET Core 2.0

推荐答案

在Firefox中,我需要保留所有的Cookie、历史记录、缓存等,但由于显而易见的原因,Selify没有构建为跨会话保存所有这些内容,因此什么都不起作用。

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

}

这篇关于不能使用C#在Selify WebDriver中使用现有的Firefox配置文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆