我如何劫持打开的浏览器会话并将其附加到Webdriver,而不是单独打开浏览器

时间:2015-02-24 09:47:50

标签: java selenium browser webdriver session-hijacking

当使用Selenium webDriver时,我总是需要启动驱动程序并打开浏览器,在流程中一直导航以验证某些内容,如果它没有抛出异常,则必须花费相同的时间。

始终考虑保持打开另一个浏览器会话,并让webdriver附加到打开的会话并对其进行处理,因此可以消除对流程的需求。

是否有人知道如何使用Java在Selenium Webdriver中执行此操作?

由于

1 个答案:

答案 0 :(得分:0)

我试过这个。它对我有用。

public class xRemoteWebDriver : RemoteWebDriver
{
    public static bool newSession;
    public static string capPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", "tmp", "sessionCap");
    public static string sessiodIdPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TestFiles", "tmp", "sessionid");

    public xRemoteWebDriver(Uri remoteAddress) 
        : base(remoteAddress, new DesiredCapabilities())
    {
    }

    protected override Response Execute(DriverCommand driverCommandToExecute, Dictionary<string, object> parameters)
    {
        if (driverCommandToExecute == DriverCommand.NewSession)
        {
            if (!newSession)
            {
                var capText = File.ReadAllText(capPath);
                var sidText = File.ReadAllText(sessiodIdPath);

                var cap = JsonConvert.DeserializeObject<Dictionary<string, object>>(capText);
                return new Response
                {
                    SessionId = sidText,
                    Value = cap
                };
            }
            else
            {
                var response = base.Execute(driverCommandToExecute, parameters);
                var dictionary = (Dictionary<string, object>) response.Value;
                File.WriteAllText(capPath, JsonConvert.SerializeObject(dictionary));
                File.WriteAllText(sessiodIdPath, response.SessionId);
                return response;
            }
        }
        else
        {
            var response = base.Execute(driverCommandToExecute, parameters);
            return response;
        }
    }
}

希望它有所帮助。