C# 当FF已打开时,Selenium无法使用配置文件打开新的firefox二进制文件

C# 当FF已打开时,Selenium无法使用配置文件打开新的firefox二进制文件,c#,selenium,webdriver,selenium-webdriver,C#,Selenium,Webdriver,Selenium Webdriver,我的应用程序使用selenium来自动化浏览器——不是为了测试应用程序,而是为了真正成为正在运行的应用程序的一部分 我正在尝试在selenium中加载FF的配置文件,但当我打开FF版本时,它不起作用。我试着用下面的方法来解决这个问题 IEnumerable<int> pidsBefore = Process.GetProcessesByName("firefox").Select(p => p.Id); FirefoxProfile profi

我的应用程序使用selenium来自动化浏览器——不是为了测试应用程序,而是为了真正成为正在运行的应用程序的一部分

我正在尝试在selenium中加载FF的配置文件,但当我打开FF版本时,它不起作用。我试着用下面的方法来解决这个问题

        IEnumerable<int> pidsBefore = Process.GetProcessesByName("firefox").Select(p => p.Id);

        FirefoxProfile profile = new FirefoxProfile(pathsToProfiles[0]);
        profile.SetPreference("browser.tabs.loadInBackground", false); // set preferences you need
        if (pidsBefore.Count() > 0)
        {
  //this next line is where I need to grab the currently open browser somehow - I know this wont work as it wont bring up the selenium webdriver plugin but ...
            driver = new FirefoxDriver((FirefoxBinary)Process.GetProcessById(pidsBefore.Last()), profile, TimeSpan.FromSeconds(30));
        }
        else
        {
            driver = new FirefoxDriver(new FirefoxBinary(), profile, TimeSpan.FromSeconds(30));
              //this also fails below

              // driver = new FirefoxDriver(profile); 
              // The process cannot access the file 'C:\Users\me\AppData\Roaming\Mozilla\Firefox\Profiles\4xcr92nu.default-1373036135509\parent.lock' because it is being used by another process.
        }
        IEnumerable<int> pidsAfter = Process.GetProcessesByName("firefox").Select(p => p.Id);
        IEnumerable<int> newFirefoxPids = pidsAfter.Except(pidsBefore);
        foreach (int pid in newFirefoxPids)
        {
            Program.newBrowserPid=pid;
   //I could kill all open instances here but I dont want to
        }
        driver.SwitchTo();

我可以关闭现有的FF实例或询问用户是否希望关闭浏览器,但这并不理想。

创建默认配置文件的副本,然后将selenium指向此复制的配置文件是解决问题的一种方法。这样,您就不必杀死其他FF进程

FirefoxProfile profile = new FirefoxProfile(@"C:\Users\YourName\AppData\Roaming\Mozilla\Firefox\Profiles\CopyOfProfile");
FirefoxDriver driver = new FirefoxDriver(profile);

如果需要它与原始配置文件保持最新,可以监视原始目录并将更改复制到副本,或者只运行定期重新复制的计划任务。根据您的自动化程度,保持它的最新可能完全没有必要。

我发现这种方法本身就有缺陷。没有真正的方法来检测浏览器实例是由Selenium还是由用户启动的。你为什么要这么做,有什么特别的原因吗?当你得到那个错误时,什么是开放的?有多少个浏览器实例?到那时,Selenium打开了多少?你打开了多少?我根本没有打开浏览器。我启动selenium以打开带有用户配置文件的浏览器,然后再次手动打开带有用户配置文件的另一个浏览器,然后启动selenium以尝试使用当前浏览器,它会抱怨锁定。另一种情况。使用默认配置文件打开一个浏览器,我尝试启动selenium以使用默认配置文件,它会抱怨锁,然后关闭正在运行的实例,重新尝试打开浏览器和配置文件,它就可以工作了。我能够获得PID,这样我就可以将选项卡添加到当前浏览器中,而不是启动新浏览器。它工作正常,我可以使用sendkeys在浏览器上打开多个选项卡。然后,我手动打开另一个浏览器启动它-然后尝试在第一个浏览器上使用selemium打开一个新选项卡,它会抱怨parent.lock。