为不同的ChromeDriver实例使用相同的chrome配置文件(会话)

我试图并行打开多个浏览器,但我无法在多个窗口中导航到该网站。

我是这样做的:

namespace XXX { public class CoreDriver { public IWebDriver driver; public int my_port { get; set; } public void Initialize() { string chromeee = ""; if (my_port == 50147) { chromeee = "C:/Users/AA/Downloads/chromedriver1/"; } else if (my_port == 50148) {chromeee = "C:/Users/AA/Downloads/chromedriver2/"; } else if (my_port == 50149) { chromeee = "C:/Users/AA/Downloads/chromedriver3/"; } else if (my_port == 50140) { chromeee = "C:/Users/AA/Downloads/chromedriver4/"; } ChromeOptions options = new ChromeOptions(); options.AddArgument("user-data-dir=C:\\Users\\AA\\AppData\\Local\\Google\\Chrome\\User Data"); var driverService = ChromeDriverService.CreateDefaultService(chromeee); driverService.HideCommandPromptWindow = true; driverService.Port = my_port; driver = new ChromeDriver(driverService, options); driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0,0,12)); driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(13)); //driver navigate } } } 

称之为:

 CoreDriver A1 = new CoreDriver(); A1.my_port = 50147; A1.Initialize(); CoreDriver A2 = new CoreDriver(); A2.my_port = 50148; A2.Initialize(); // timeout error here // ... 

不幸的是,在第二个窗口打开后 – 显示超时错误:

WebDriver.dll中出现“OpenQA.Selenium.WebDriverException”类型的第一次机会exception

附加信息:远程WebDriver服务器对URL http:/ loca1host:50148 / session的HTTP请求在60秒后超时。

在这一行:

driver = new ChromeDriver(driverService,options);

在使用不同参数重新运行测试后,我发现由于指定的Chrome配置文件而显示错误:

 options.AddArgument("user-data-dir=C:\\Users\\AA\\AppData\\Local\\Google\\Chrome\\User Data"); 

如果我删除该行 – 那么我的所有Cookie都不会在ChromeDriver实例中使用,而这不是我可以使用的东西:)有没有办法在多个chromedriver实例中使用相同的chrome配置文件?

好的,所以我正在使用我的方法,如上所述。

我的要求是:

  • 我必须保留主要铬配置文件的cookie
  • 我必须保留主要配置文件的扩展名
  • 我不需要主要配置文件的历史记录,打开的标签,会话等
  • 在新的现有自定义配置文件启动后 – 我在没有打开标签的情况下开始清除它

这是几句话的逻辑。

  • 首先,我指定现有Google Chrome配置文件的目录。
  • 如果我们需要创建cookie(即登录某个网站),那么我们在谷歌浏览器的主要配置文件上进行。
  • 完成后,关闭铬。 有些网站会长时间保留cookie,有些则不然。 因此,在必要时重新登录主要配置文件符合我们的利益。 不要保持原始镀铬打开! 否则ChromeDriver会抛出一些警告。
  • 接下来,我的脚本会将必要的文件夹和文件复制到新文件夹中。 此文件夹是包含所有Cookie的新配置文件。 在我的电脑上,一切都是大约30兆字节
  • 如果新配置文件的文件夹已存在 – 则程序将仅复制cookie文件。 这不应该超过1-2兆的数据。

这是代码。 你可能想要调整一件事或另一件事。

 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.Support.UI; using OpenQA.Selenium.Internal; using OpenQA.Selenium.Remote; using System.IO; using System.Drawing.Imaging; using System.Management; using System.Text.RegularExpressions; using System.Threading; using System.Diagnostics; using System.Reflection; using System.Threading.Tasks; using System.Collections.Concurrent; using System.Runtime.InteropServices; using System.Net; namespace NAMESPACE { public class CoreDriver { public IWebDriver driver; public string my_name { get; set; } public int my_port { get; set; } public string default_profile_dir = @"C:\Users\USERNAME\AppData\Local\Google\Chrome\"; public string chromedriver_path = @"C:\Users\USERNAME\Downloads\chromedriver_win32\"; public string site_profile_path; public string site_profile_path_s; public string default_path; public void Initialize() { ChromeOptions options = new ChromeOptions(); options.AddArgument("--log-level=3"); options.AddArgument("--test-type"); options.AddArgument("--silent"); options.AddArgument("user-data-dir=" + site_profile_path_s); options.AddArgument("--disable-plugins"); // disable flash var driverService = ChromeDriverService.CreateDefaultService(chromedriver_path); driverService.HideCommandPromptWindow = true; driverService.Port = my_port; driver = new ChromeDriver(driverService, options); driver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 14)); driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(15)); IJavaScriptExecutor jscript = driver as IJavaScriptExecutor; jscript.ExecuteScript("return window.stop"); } public void ConfigureProfile() { site_profile_path_s = default_profile_dir + "profile " + my_name; site_profile_path = site_profile_path_s + @"\Default"; default_path = default_profile_dir + @"User Data\Default"; if (!Directory.Exists(site_profile_path)) { CreateBlankProfile(); } else { // copy existing chrome profile. Keep cache, extensions, etc. CopyProfileFiles(); // but stay away from opened tabs RemoveOpenedTabsFiles(); } } public void CleanUpOldProfiles() { DirectoryInfo di = new DirectoryInfo(default_profile_dir); DirectoryInfo[] directories = di.GetDirectories("profile*", SearchOption.TopDirectoryOnly); if (directories.Count() > 0) { foreach (var folder in directories) { try { Directory.Delete(folder.FullName, true); } catch { } } } } public void CreateBlankProfile() { // new profile direftory CreateIfMissing(); // copy existing chrome profile. Keep cache, extensions, etc. // but stay away from opened tabs CopyProfileFiles(); CopyProfileFolders(); } public void CopyProfileFiles() { // default profile location DirectoryInfo di = new DirectoryInfo(default_path); // copy files List file_lib = new List() { "Cookies", "Login", "Preferences", "Secur" }; FileInfo[] files = di.GetFiles("*", SearchOption.TopDirectoryOnly); if (files.Count() > 0) { foreach (var file in files) { if (PassFileOrFolder(file.Name, file_lib)) { file.CopyTo(site_profile_path + @"\" + file.Name, true); } } } } public void RemoveOpenedTabsFiles() { // default profile location DirectoryInfo di = new DirectoryInfo(site_profile_path); // copy files List file_lib = new List() { "Current", "Last" }; FileInfo[] files = di.GetFiles("*", SearchOption.TopDirectoryOnly); if (files.Count() > 0) { foreach (var file in files) { if (PassFileOrFolder(file.Name, file_lib)) { File.Delete(file.FullName); } } } } public void CopyProfileFolders() { // default profile location DirectoryInfo di = new DirectoryInfo(default_path); // copy folders List folder_lib = new List() { "databases", "Extension", " Storage", "Web Applications", "File System", "IndexedDB" }; DirectoryInfo[] directories = di.GetDirectories("*", SearchOption.TopDirectoryOnly); if (directories.Count() > 0) { foreach (var folder in directories) { if (PassFileOrFolder(folder.Name, folder_lib)) { DirectoryCopy(folder.FullName, site_profile_path + @"\" + folder.Name, true); } } } } private void CreateIfMissing() { Directory.CreateDirectory(site_profile_path); } private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { // Get the subdirectories for the specified directory. DirectoryInfo dir = new DirectoryInfo(sourceDirName); DirectoryInfo[] dirs = dir.GetDirectories(); if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirName); } // If the destination directory doesn't exist, create it. if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } // Get the files in the directory and copy them to the new location. FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { string temppath = Path.Combine(destDirName, file.Name); file.CopyTo(temppath, false); } // If copying subdirectories, copy them and their contents to new location. if (copySubDirs) { foreach (DirectoryInfo subdir in dirs) { string temppath = Path.Combine(destDirName, subdir.Name); DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } } public bool PassFileOrFolder(string input, List library) { foreach (string name in library) { if (input.Contains(name)) { return true; } } return false; } } } 

请注意,我还实现了一种方法来清理所有配置文件CleanUpOldProfiles

查看代码,更改目录等。完成后 – 进行以下调用:

 CoreDriver something = new CoreDriver(); // creating an object // settings something.my_port = 50150; // multiple chrome instances - will be run on different ports // I am currently having 4 chrome profiles ;) something.my_name = "mynewprofile"; // full profile name will be: 'profile + my_name'. Check the code of the object. // void something.ConfigureProfile(); // creating new profile or updating existing one, if folder eists something.Initialize(); // starting the browser 

抱歉,答案很长。 希望它能以某种方式帮助你们:)