Starting a specific Firefox Profile with Selenium 3

后端 未结 1 882
广开言路
广开言路 2021-01-02 11:26

I am trying to upgrade from Selenium 2 to Selenium 3 but the old handling, which was pretty easy and fast doesn\'t work anymore (and the documentation is nonexisting as it s

相关标签:
1条回答
  • 2021-01-02 11:40

    This exception is due to a bug in the .Net library. The code generating the Zip of the profile is failing to provide a proper Zip.

    One way to overcome this issue would be to overload FirefoxOptions and use the archiver from .Net framework (System.IO.Compression.ZipArchive) instead of the faulty ZipStorer:

    var options = new FirefoxOptionsEx();
    options.Profile = @"C:\Users\...\AppData\Roaming\Mozilla\Firefox\Profiles\ez3krw80.Selenium";
    options.SetPreference("network.proxy.type", 0);
    
    var service = FirefoxDriverService.CreateDefaultService(@"C:\downloads", "geckodriver.exe");
    
    var driver = new FirefoxDriver(service, options, TimeSpan.FromMinutes(1));
    
    class FirefoxOptionsEx : FirefoxOptions {
    
        public new string Profile { get; set; }
    
        public override ICapabilities ToCapabilities() {
    
            var capabilities = (DesiredCapabilities)base.ToCapabilities();
            var options = (IDictionary)capabilities.GetCapability("moz:firefoxOptions");
            var mstream = new MemoryStream();
    
            using (var archive = new ZipArchive(mstream, ZipArchiveMode.Create, true)) {
                foreach (string file in Directory.EnumerateFiles(Profile, "*", SearchOption.AllDirectories)) {
                    string name = file.Substring(Profile.Length + 1).Replace('\\', '/');
                    if (name != "parent.lock") {
                        using (Stream src = File.OpenRead(file), dest = archive.CreateEntry(name).Open())
                            src.CopyTo(dest);
                    }
                }
            }
    
            options["profile"] = Convert.ToBase64String(mstream.GetBuffer(), 0, (int)mstream.Length);
    
            return capabilities;
        }
    
    }
    

    And to get the directory for a profile by name:

    var manager = new FirefoxProfileManager();
    var profiles = (Dictionary<string, string>)manager.GetType()
        .GetField("profiles", BindingFlags.Instance | BindingFlags.NonPublic)
        .GetValue(manager);
    
    string directory;
    if (profiles.TryGetValue("Selenium", out directory))
        options.Profile = directory;
    
    0 讨论(0)
提交回复
热议问题