java - 如何仅使用 session ID 或现有 webdriver session 的 cookie 来获取 webdriver 对象

标签 java selenium selenium-webdriver selenium-chromedriver

我有一种情况,webdriver 对象隐藏在依赖项项目的包装器中,我只能检索字符串格式的 session ID 并从这些函数返回 driver.manage()/cookies。

现在我尝试使用此 session ID 并将其传递给我的 webdriver 引用变量,以便我可以扩展我的要求。

我还找到了与以下相同的引用:

https://tarunlalwani.com/post/reusing-existing-browser-session-selenium-java/

我尝试过,但出现以下错误:

Exception in thread "main" org.openqa.selenium.json.JsonException: Unable to determine type from: <. Last 1 characters read: < Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03' System info: host: 'xxxxxx', ip: 'xxx.xx.xx.xx', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_151'

带有 cookie 的代码:

public static void main(String[] args) throws URISyntaxException, MalformedURLException {
    WebDriver driver = null;

    //WebDriverManager.chromedriver().setup();
    WebDriverManager.chromedriver().version(Configuration.getConfigurationValueForProperty("chrome-version"))
            .setup();
    ChromeOptions options = new ChromeOptions();
    options.addArguments("start-maximized");
    options.addArguments("enable-automation");
    // options.addArguments("--headless");
    options.addArguments("--no-sandbox");
    options.addArguments("--disable-infobars");
    options.addArguments("--disable-dev-shm-usage");
    options.addArguments("--disable-browser-side-navigation");
    options.addArguments("--disable-gpu");
    driver = new ChromeDriver(options);
    driver.get(Configuration.applicationUnderTestURL());

    Set<Cookie> name =driver.manage().getCookies();

    WebDriver driver3 = null;

    for(Cookie test: name) 
    {
        driver3.manage().addCookie(test);
    }

    driver3.get("https://stackoverflow.com/questions/8638241/setting-cookie-through-foreach-loop-inside-while-loop");

}

我尝试使用 session ID 来演示代码:

package stepdef;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collections;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.Command;
import org.openqa.selenium.remote.CommandExecutor;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.Response;
import org.openqa.selenium.remote.SessionId;
import org.openqa.selenium.remote.http.W3CHttpCommandCodec;
import org.openqa.selenium.remote.http.W3CHttpResponseCodec;

import automationframework.Configuration;
import io.github.bonigarcia.wdm.WebDriverManager;

public class testing {

public static void main(String[] args) throws URISyntaxException, MalformedURLException {
    WebDriver driver = null;

    //WebDriverManager.chromedriver().setup();
    WebDriverManager.chromedriver().version(Configuration.getConfigurationValueForProperty("chrome-version"))
            .setup();
    ChromeOptions options = new ChromeOptions();
    options.addArguments("start-maximized");
    options.addArguments("enable-automation");
    // options.addArguments("--headless");
    options.addArguments("--no-sandbox");
    options.addArguments("--disable-infobars");
    options.addArguments("--disable-dev-shm-usage");
    options.addArguments("--disable-browser-side-navigation");
    options.addArguments("--disable-gpu");
    driver = new ChromeDriver(options);
    driver.get(Configuration.applicationUnderTestURL());

    SessionId session = ((ChromeDriver)driver).getSessionId();

    String session2 = session.toString();

    System.out.println(session2);

    String str = "http://google.com"; // just passing random URL as I have only session id
    URI uri = new URI(str);
    URL url = uri.toURL();


    RemoteWebDriver driver2 = createDriverFromSession(session, url);    
    driver2.get("http://tarunlalwani.com"); // here I am getting error where I need to resue the existing browser using session id



}

public static RemoteWebDriver createDriverFromSession(final SessionId sessionId, URL command_executor){
    CommandExecutor executor = new HttpCommandExecutor(command_executor) {

    @Override
    public Response execute(Command command) throws IOException {
        Response response = null;
        if (command.getName() == "newSession") {
            response = new Response();
            response.setSessionId(sessionId.toString());
            response.setStatus(0);
            response.setValue(Collections.<String, String>emptyMap());

            try {
                Field commandCodec = null;
                commandCodec = this.getClass().getSuperclass().getDeclaredField("commandCodec");
                commandCodec.setAccessible(true);
                commandCodec.set(this, new W3CHttpCommandCodec());

                Field responseCodec = null;
                responseCodec = this.getClass().getSuperclass().getDeclaredField("responseCodec");
                responseCodec.setAccessible(true);
                responseCodec.set(this, new W3CHttpResponseCodec());
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        } else {
            response = super.execute(command);
        }
        return response;
    }
    };

    return new RemoteWebDriver(executor, new DesiredCapabilities());
}
}

如果可能或有其他办法,请告诉我

最佳答案

尝试修改现有 WebDriver 对象的 Options 似乎是 not possible 。这意味着尝试修改现有 WebDriver 对象的 cookie 或 session ID 也是不可能的。

这里唯一的解决方法是创建一个新的 WebDriver 实例。但是,创建新的 WebDriver 实例是 OP 施加的限制,因此这是不可行的。

关于java - 如何仅使用 session ID 或现有 webdriver session 的 cookie 来获取 webdriver 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59566324/

相关文章:

java - 使用ant编译java类: cannot find symbol

python - 带有 python 的 Selenium webdriver-如果加载时间太长,如何重新加载页面?

ruby - 使用 Capybara SitePrism 等待图像加载

java - 如何在java中打印RowMatrix的元素?

java - 为注册和确认设计定制

java - 为什么双击显示日期对话框

java - 使用 Selenium IEDriverServer 的文本输入速度非常慢?

webdriver - cssSelector 中 contains 的替代方法? Selenium 网络驱动程序

selenium-webdriver - 如何使用 selenium 为 firefox 浏览器禁用通知

java - 在本地计算机上使用 Java 从服务器打开目录