Connecting Selenium WebDriver to an existing brows

2019-05-27 20:54发布

I am working with selenium and I would like to attach a webdriver instance if an existing browser session (for me Chrome) currently exists. I don't want to open a new Browser window/session. I have googled and seen, that there are some ways to do this with the description on these sites:

  1. Reuse existing Browser Session by extending RemoteWebDriver
  2. Basic Stuff for ChromeDriverService

I'am using ChromeDriver 2.29 in the latest version.

My code is looking now as follows:

public static void main(String[] args) throws Exception {
    // starting Chrome Webdriver server
    ChromeDriverService service = new ChromeDriverService.Builder()
            .usingDriverExecutable(new File("D:\\Development\\chromedriver\\chromedriver.exe"))
            .usingAnyFreePort()
            .build();
    service.start();

    WebDriver driver = new CustomRemoteWebDriver(service.getUrl(),DesiredCapabilities.chrome());
    driver.get("http://www.google.com");
    WebDriver driver2 = new CustomRemoteWebDriver(service.getUrl(),DesiredCapabilities.chrome());
    // here I am expecting www.google.com from last driver instance, because it should have the same session
    System.out.println(driver2.getCurrentUrl());
    driver.quit();
    driver2.quit();
}

The extended RemoteWebDriver, that checks if a session already exists:

public class CustomRemoteWebDriver extends RemoteWebDriver {
    public static String sessiondIdPath = "c:\\automation\\sessionid";

    public CustomRemoteWebDriver(URL remoteAddress, Capabilities desiredCapabilities) {
        super(remoteAddress, desiredCapabilities);
    }

    @Override
    protected void startSession(Capabilities desiredCapabilities) {
        String sid = getPreviousSessionIdFromSomeStorage();
        if (sid != null) {
            setSessionId(sid);
            try {
                getCurrentUrl();
            } catch (WebDriverException e) {
                // session is not valid
                e.printStackTrace();
                sid = null;
            }
        }

        if (sid == null) {
            super.startSession(desiredCapabilities);
            saveSessionIdToSomeStorage(getSessionId().toString());
        }
    }

    private void saveSessionIdToSomeStorage(String sessionId) {
        try {
            FileUtils.writeStringToFile(new File(sessiondIdPath), sessionId, Charset.defaultCharset());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String getPreviousSessionIdFromSomeStorage() {
        String sessionId;
        try {
            List<String> sidText = FileUtils.readLines(new File(sessiondIdPath), Charset.defaultCharset());
            sessionId = sidText.get(0);
        } catch (Exception e) {
            return null;
        }
        return sessionId;
    }
}

and the pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.andy.selenium</groupId>
    <artifactId>remotewebdriverexample</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>3.4.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.appium/java-client -->
        <dependency>
            <groupId>io.appium</groupId>
            <artifactId>java-client</artifactId>
            <version>4.1.2</version>
        </dependency>
    </dependencies>

    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.6.1</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

Assuming I have no sessionId currently saved: Starting driver1 and going to www.google.com works as expected. On the initialization of driver2 an WebDriverException is thrown in the CustomRemoteWebDriver#startSession. So it is printing the stacktrace and the sessionId seems to be invalid. The output with the stacktrace is the following:

Starting ChromeDriver 2.29.461591 (62ebf098771772160f391d75e589dc567915b233) on port 31495 Only local connections are allowed. Mai 25, 2017 6:53:14 PM org.openqa.selenium.remote.ProtocolHandshake createSession INFORMATION: Detected dialect: OSS

org.openqa.selenium.WebDriverException: No command or response codec has been defined. Unable to proceed Build info: version: '3.4.0', revision: 'unknown', time: 'unknown' System info: host: 'DESKTOP-AGEFV4C', ip: '192.168.134.1', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_121' Driver info: driver.version: CustomRemoteWebDriver at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:154) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:637) at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:694) at org.openqa.selenium.remote.RemoteWebDriver.getCurrentUrl(RemoteWebDriver.java:374) at CustomRemoteWebDriver.startSession(CustomRemoteWebDriver.java:57) at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:137) at org.openqa.selenium.remote.RemoteWebDriver.(RemoteWebDriver.java:174) at CustomRemoteWebDriver.(CustomRemoteWebDriver.java:22) at RemoteBrowserConnector.start(RemoteBrowserConnector.java:40) at RemoteBrowserConnector.main(RemoteBrowserConnector.java:26) Mai 25, 2017 6:53:18 PM org.openqa.selenium.remote.ProtocolHandshake createSession INFORMATION: Detected dialect: OSS

I have already tried it by updating the java client, which was suggested by this post, but it doesn't help. A new window is always opened, because of this exception. Any idea, what I'm doing wrong?

0条回答
登录 后发表回答