【问题标题】:Use Selenium with same browser session将 Selenium 与相同的浏览器会话一起使用
【发布时间】:2018-06-26 12:00:48
【问题描述】:
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;

public class Test1 {
  private WebDriver driver;
  private String baseUrl;
  private boolean acceptNextAlert = true;
  private StringBuffer verificationErrors = new StringBuffer();

  @Before
  public void setUp() throws Exception {
    System.setProperty("webdriver.ie.driver",  "D:/Development/ProgrammingSoftware/Testing/IEDriverServer.exe");

    WebDriver driver = new InternetExplorerDriver();
    baseUrl = "http://seleniumhq.org/";
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
  }

  @Test
  public void test1() throws Exception {
    driver.get(baseUrl + "/download/");
    driver.findElement(By.linkText("Latest Releases")).click();
    driver.findElement(By.linkText("All variants of the Selenium Server: stand-alone, jar with dependencies and sources.")).click();
  }

  @After
  public void tearDown() throws Exception {
    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!"".equals(verificationErrorString)) {
      fail(verificationErrorString);
    }
  }

  private boolean isElementPresent(By by) {
    try {
      driver.findElement(by);
      return true;
    } catch (NoSuchElementException e) {
      return false;
    }
  }

  private String closeAlertAndGetItsText() {
    try {
      Alert alert = driver.switchTo().alert();
      if (acceptNextAlert) {
        alert.accept();
      } else {
        alert.dismiss();
      }
      return alert.getText();
    } finally {
      acceptNextAlert = true;
    }
  }
}

我希望 IE 具有相同的会话,但此代码总是打开一个新的 IE 实例。我如何获得这项工作?

【问题讨论】:

  • 什么意思?您希望 IEDriver 附加到现有会话吗?您想要一个 IEDriver 用于整套测试吗?你有多少个测试
  • 我对Junit不太熟悉,但是上面的代码不会抛出NPE吗?因为你在你的 before 方法中重新声明了 Webdriver 而没有真正实例化类的私有 var ..

标签: testing selenium junit


【解决方案1】:

我认为不可能将驱动程序附加到现有会话。

如果您已经执行完一个测试方法,并且如果您想执行另一个类或包中存在的另一个测试方法,请通过将当前驱动程序传递给该方法来调用该方法,以便您可以使用当前的实例那边的司机。

【讨论】:

    【解决方案2】:

    这个问题在过去已经被问过好几次了,而我要回答的问题甚至都不是最近的。但是我仍然会继续发布答案,因为最近我被与同一浏览器会话相关的问题所困扰。我如何能够利用已经打开的浏览器,这样我就可以继续我的测试运行,而不是从头开始重新启动它。在浏览大量页面后,当您遇到重新启动 Selenium 测试的问题时,在某些情况下甚至会很费力。相反,我想知道“银弹在哪里?”。终于看到了“http://tarunlalwani.com/post/reusing-existing-browser-session-selenium/”写的一篇文章。但是仍然有一些缺失的链接。所以我想在这里借助一个合适的例子来解开它。 在以下代码 sn-p 中,我尝试在 Chrome 浏览器的 Selenium 会话中启动 SeleniumHQ 并单击下载链接。

        System.setProperty("webdriver.chrome.driver","C:\\Selenium\\chromedriver.exe");
    //First Session
            ChromeDriver driver = new ChromeDriver();
            HttpCommandExecutor executor = (HttpCommandExecutor) 
            driver.getCommandExecutor();
            URL url = executor.getAddressOfRemoteServer();
            SessionId session_id = driver.getSessionId();
            storeSessionAttributesToFile("Id",session_id.toString());
            storeSessionAttributesToFile("URL",url.toString());
            driver.get("https://docs.seleniumhq.org/");
            WebElement download = driver.findElementByLinkText("Download");
            download.click();
    

    如果您阅读了上面的代码,我将捕获 Selenium 远程服务器的 URL 和当前 selenium(浏览器)会话的会话 ID,并将其写入属性文件。 现在,如果我需要继续在同一个浏览器窗口/会话中执行,尽管停止了当前的测试运行,我需要做的就是在上述代码 sn-p 中注释第一个会话下方的代码并继续从代码中进行测试下面:

    System.setProperty("webdriver.chrome.driver","C:\\Selenium\\chromedriver.exe");
    //First Session
      //ChromeDriver driver = new ChromeDriver();
      //HttpCommandExecutor executor = (HttpCommandExecutor) driver.getCommandExecutor();
     //URL url = executor.getAddressOfRemoteServer();
    //SessionId session_id = driver.getSessionId();
    //storeSessionAttributesToFile("Id",session_id.toString());
    //      storeSessionAttributesToFile("URL",url.toString());
    //      driver.get("https://docs.seleniumhq.org/");
    //      WebElement download = driver.findElementByLinkText("Download");
    //      download.click();
    //Attaching to the session
        String existingSession = readSessionId("Id");
        String url1 = readSessionId("URL");
        URL existingDriverURL = new URL(url1);
        RemoteWebDriver attachToDriver = createDriverFromSession(existingSession, existingDriverURL);
        WebElement previousReleases = attachToDriver.findElementByLinkText("Previous Releases");
        previousReleases.click();
    

    现在您可能必须重构和重命名驱动程序对象(即使保留名称仍然可以,但我只是想区分将其附加到现有驱动程序和启动驱动程序)。在上面的代码块中,我在读取并分配 URL 和 sessionid 并从会话创建驱动程序以继续利用浏览器和会话之后继续我的测试。 请查看下面的完整代码:

    package org.openqa.selenium.example;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.lang.reflect.Field;
    import java.net.URL;
    import java.util.Collections;
    import java.util.Properties;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.chrome.ChromeDriver;
    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;
    
    public class AttachingToSession {
    
    public static String SESSION_FILE = "C:\\example\\Session.Properties";
    public static Properties prop = new Properties();
    
    public static void main(String[] args) throws Exception {
        System.setProperty("webdriver.chrome.driver","C:\\Selenium\\chromedriver.exe");
    //First Session
        ChromeDriver driver = new ChromeDriver();
        HttpCommandExecutor executor = (HttpCommandExecutor) driver.getCommandExecutor();
        URL url = executor.getAddressOfRemoteServer();
        SessionId session_id = driver.getSessionId();
        storeSessionAttributesToFile("Id",session_id.toString());
        storeSessionAttributesToFile("URL",url.toString());
        driver.get("https://docs.seleniumhq.org/");
        WebElement download = driver.findElementByLinkText("Download");
        download.click();
    //Attaching to the session
        String existingSession = readSessionId("Id");
        String url1 = readSessionId("URL");
        URL existingDriverURL = new URL(url1);
        RemoteWebDriver attachToDriver = createDriverFromSession(existingSession, existingDriverURL);
        WebElement previousReleases = attachToDriver.findElementByLinkText("Previous Releases");
        previousReleases.click();
    }
    
    public static RemoteWebDriver createDriverFromSession(final String 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);
                    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());
    }
    
    
    public static void storeSessionAttributesToFile(String key,String value) throws Exception{
            OutputStream output = null;
            try{
                output = new FileOutputStream(SESSION_FILE);
                //prop.load(output);
                prop.setProperty(key, value);
                prop.store(output, null);
            }
            catch(IOException e){
                e.printStackTrace();
            }
            finally {
                if(output !=null){
                    output.close();
                }
            }
    
    }
    
    public static String readSessionId(String ID) throws Exception{
    
        Properties prop = new Properties();
        InputStream input = null;
        String SessionID = null;
        try {
            input = new FileInputStream(SESSION_FILE);
            // load a properties file
            prop.load(input);
            // get the property value and print it out
            System.out.println(prop.getProperty(ID));
            SessionID = prop.getProperty(ID);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return SessionID;
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-12-26
      • 2013-08-17
      • 1970-01-01
      • 2016-08-02
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      • 2014-01-24
      • 2018-09-20
      相关资源
      最近更新 更多