问题
What is the Use of SessionID in Selenium Webdriver?
Consider a scenario having opened 5 Browsers each having its own sessionid. Can we use these sessionid's to close their respective browsers ? if so, how do we do that in C# ?
回答1:
Having session ID handy could help you connect with your session on a remote web driver. You can fetch the session ID with :
var sessionIdProperty = typeof(RemoteWebDriver).GetProperty("sessionId", BindingFlags.Instance | BindingFlags.NonPublic); //sessionId
if (sessionIdProperty != null)
{
SessionId sessionId = sessionIdProperty.GetValue(driver, null) as SessionId;
sId = sessionId.ToString();//((RemoteWebDriver)driver).Capabilities.GetCapability("webdriver.remote.sessionid").ToString();
}
After that - You may be able to reconnect to the session by using :
IWebDriver driverReUse = new ReuseRemoteWebDriver(uri, sId);
Given that you have a class that allows reuse of a remote webdriver.
public class ReuseRemoteWebDriver : OpenQA.Selenium.Remote.RemoteWebDriver
{
private String _sessionId;
public ReuseRemoteWebDriver(Uri remoteAddress, String sessionId)
: base(remoteAddress, new OpenQA.Selenium.Remote.DesiredCapabilities())
{
this._sessionId = sessionId;
var sessionIdBase = this.GetType()
.BaseType
.GetField("sessionId",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic);
sessionIdBase.SetValue(this, new OpenQA.Selenium.Remote.SessionId(sessionId));
}
protected override OpenQA.Selenium.Remote.Response
Execute(string driverCommandToExecute, System.Collections.Generic.Dictionary<string, object> parameters)
{
if (driverCommandToExecute == OpenQA.Selenium.Remote.DriverCommand.NewSession)
{
var resp = new OpenQA.Selenium.Remote.Response();
resp.Status = OpenQA.Selenium.WebDriverResult.Success;
resp.SessionId = this._sessionId;
resp.Value = new System.Collections.Generic.Dictionary<String, Object>();
return resp;
}
var respBase = base.Execute(driverCommandToExecute, parameters);
return respBase;
}
}
回答2:
In general, the session ID is an internal implementation detail with which an end user should not have to concern themselves. A browser session can be terminated, along with the running browser instance, by calling the .Quit()
method. To wit:
// Launch one instance of Firefox
IWebDriver driver1 = new FirefoxDriver();
// Launch a second instance of Firefox,
// which can be controlled independently
// of the first.
IWebDriver driver2 = new FirefoxDriver();
// Exit the first Firefox instance (the second
// remains running.
driver1.Quit();
// Exit the second instance.
driver2.Quit();
However, it must be noted that WebDriver can only manipulate browser instances started via WebDriver. There is no way at present to connect to an existing, running browser instance, nor is there likely to be.
来源:https://stackoverflow.com/questions/25129960/selenium-webdriver-in-c-sharp-usage-of-sessionid