Selenium系列之--08 操作已打開的瀏覽器


參考文章:Can Selenium interact with an existing browser session?

 

1. 建一個ReuseWebDriver類

import java.io.IOException;
import java.net.URL;

import org.openqa.selenium.remote.Command;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.HttpCommandExecutor;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.Response;

public class ReuseWebDriver extends RemoteWebDriver {

    public ReuseWebDriver(URL url, String sessionId) {
        super();
        setSessionId(sessionId);
        setCommandExecutor(new HttpCommandExecutor(url) {
            @Override
            public Response execute(Command command) throws IOException {
                if (command.getName() != "newSession") {
                    return super.execute(command);
                }
                return super.execute(new Command(getSessionId(),
                        "getCapabilities"));
            }
        });
        startSession(new DesiredCapabilities());
    }
}

2. 調用

public class ReuseIEDriverTest {

    public static void main(String[] args) throws MalformedURLException {
        -------
        // 初始化一個IE瀏覽器實例
        InternetExplorerDriver driver = new InternetExplorerDriver(
                ieCapabilities);
        // 最大化窗口
        driver.manage().window().maximize();
        // get()打開一個站點
        driver.get("https://www.baidu.com");
        // getTitle()獲取當前頁面title的值
        System.out.println("當前打開頁面的標題是: " + driver.getTitle());
        SessionId sessionId = driver.getSessionId();
        URL url = ((HttpCommandExecutor) driver.getCommandExecutor())
                .getAddressOfRemoteServer();
        System.out.println(sessionId);
        System.out.println(url);

        // 初始化一個chrome瀏覽器實例,實例名稱叫driver
        ReuseWebDriver2 redriver = new ReuseWebDriver2(url,sessionId.toString());
        // get()打開一個站點
        redriver.get("https://www.bing.com");
        // getTitle()獲取當前頁面title的值
        System.out.println("當前打開頁面的標題是: " + redriver.getTitle());
        System.out.println(redriver.getSessionId());
        System.out.println(redriver.getCapabilities());
        System.out.println(((HttpCommandExecutor) redriver.getCommandExecutor())
                .getAddressOfRemoteServer());
        redriver.executeScript("alert(\"hello,this is an alert!\")");
        // 關閉並退出瀏覽器
        // driver.quit();
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM