I'm trying to run 2 chrome browser instances with selenium webdriver library. However Even if these two browsers were initiated separately and are in separate threads, the code controls and manipulates only one browser.
The code for creating a chrome browser and perform the testing
static void test(string url)
{
ChromeDriver driver = BrowserWorker.GetChromeBrowser(false);
driver.Navigate().GoToUrl(url);
}
The "BrowserWorkser.GetChromeBrowser" function is to return a customized chrome browser instance:
public static ChromeDriver GetChromeBrowser()
{
var chromeoptions = new ChromeOptions();
chromeoptions.AddArguments("--disable-notifications");
chromeoptions.AddArguments("--no-sandbox");
chromeoptions.AddArguments("--disable-dev-shm-usage");
chromeoptions.UnhandledPromptBehavior = UnhandledPromptBehavior.Dismiss;
chromeoptions.AddArguments("--remote-debugging-port=9222");
var chromeDriverService = ChromeDriverService.CreateDefaultService(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
chromeDriverService.HideCommandPromptWindow = true;
ChromeDriver browser = null;
int nCount = 0;
while (browser == null && nCount < 3)
{
try
{
browser = new ChromeDriver(chromeDriverService, chromeoptions, TimeSpan.FromSeconds(180));
}
catch (Exception ex)
{
Console.WriteLine("Error initializing chrome browser: " ex.Message);
}
nCount ;
}
return browser;
}
First method:
var t1 = new Thread(() => test("https://www.google.com/"));
var t2 = new Thread(() => test("https://www.bing.com/"));
t1.Start();
t2.Start();
Second method, changed the signature of "test(string url)" to "async Task" and added "await Task.Delay(1);", so the compiler does not complain:
var list = new List<Task>();
list.Add(test("https://www.google.com/"));
list.Add(test("https://www.bing.com/"));
Task.WaitAll(list.ToArray());
However neither method worked. The two separate threads/tasks controls the same browser instance, it loads google and bing, in a random order. Please let me know if you need additional information. Thank you.
CodePudding user response:
If you launch Chrome with different arguments, it launches a new instance. So in this case making --remote-debugging-port
to be in different port will make the driver launch a new instance instead of using the existing instance.