问题
Here is my Code:
var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("headless");
_driver = new OpenQA.Selenium.Chrome.ChromeDriver(chromeOptions);
_driver.Navigate().GoToUrl(url);
It will open an instance of chromedriver.exe and will navigate to the target URL. I need to navigate to other URLs with the same chromedriver.exe intance, and I need to set specific headers and cookies for each URL.
How to achieve something with Selenium and ChromeDriver?
回答1:
Personally, i;d do this with multiple browser instances. They shouldn't leak state between them and it makes start up, cleandown and management much easier.
However - if you must use tabs, something like this would help...
This is a simple manager:
class BrowserManager
{
private IWebDriver driver;
public BrowserManager()
{
//do your browser options here
driver = new ChromeDriver();
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30);
}
public IWebDriver getDriver()
{
return driver;
}
public void addTab(string url)
{
var js = $"window.open('{url}','_blank');";
((IJavaScriptExecutor)driver).ExecuteScript(js);
var handles = driver.WindowHandles.ToArray<string>();
driver.SwitchTo().Window(handles[handles.Length -1]); //switch to latest tab
driver.Navigate().GoToUrl(url);
}
public void activateTabForPartialURL(string url)
{
var handles = driver.WindowHandles;
foreach (var handle in handles)
{
driver.SwitchTo().Window(handle);
if (driver.Url.Contains(url))
return;
}
}
}
This is how you use it. Plenty more ways to find the tabs you want, this is just a quick example
class UsingTheBrowserManager
{
[Test]
public void usingIt()
{
string google = "https://www.google.com";
string stackoverflow = "https://stackoverflow.com";
var browserManager = new BrowserManager();
var driver = browserManager.getDriver();
//create all your drivers:
browserManager.addTab(google);
browserManager.addTab(stackoverflow);
//Do your cookie/header work
//...
//pick and tab and doing an action or get some data
browserManager.activateTabForPartialURL("google");
Debug.WriteLine(browserManager.getDriver().Title);
browserManager.activateTabForPartialURL("stackoverflow");
Debug.WriteLine(browserManager.getDriver().Title);
}
}
来源:https://stackoverflow.com/questions/62774094/creating-new-tabs-and-managing-them-selenium