Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
维护和重用现有webdriver浏览器实例-java_Java_Selenium_Selenium Webdriver_Browser Automation_Remotewebdriver - Fatal编程技术网

维护和重用现有webdriver浏览器实例-java

维护和重用现有webdriver浏览器实例-java,java,selenium,selenium-webdriver,browser-automation,remotewebdriver,Java,Selenium,Selenium Webdriver,Browser Automation,Remotewebdriver,基本上,每次我从eclipse运行java代码时,webdriver都会启动一个新的ie浏览器,并在大部分情况下成功地执行我的测试。然而,我有很多测试要运行,webdriver每次启动一个新的浏览器会话都很痛苦。我需要一种重新使用以前打开的浏览器的方法;所以webdriver会在第一次打开ie,然后第二次,我运行我的eclipse程序,我希望它能够简单地获取以前的浏览器实例,并继续在同一个实例上运行我的测试。这样,我就不会每次运行程序时都启动新的浏览器会话 假设您有100个测试要在eclipse

基本上,每次我从eclipse运行java代码时,webdriver都会启动一个新的ie浏览器,并在大部分情况下成功地执行我的测试。然而,我有很多测试要运行,webdriver每次启动一个新的浏览器会话都很痛苦。我需要一种重新使用以前打开的浏览器的方法;所以webdriver会在第一次打开ie,然后第二次,我运行我的eclipse程序,我希望它能够简单地获取以前的浏览器实例,并继续在同一个实例上运行我的测试。这样,我就不会每次运行程序时都启动新的浏览器会话

假设您有100个测试要在eclipse中运行,点击run按钮,它们都会运行,然后在大约第87次测试时,您会得到一个错误。然后返回eclipse,修复该错误,但随后必须从头开始重新运行所有100个测试

修复第87个测试上的错误,然后从第87个测试恢复执行,这将是很好的,而不是从头开始重新执行所有测试,即从测试0一直执行到100。 希望我很清楚能得到你们的帮助,谢谢。

下面是我试图维护和重用webdriver internet explorer浏览器实例的尝试:

public class demo extends RemoteWebDriver { 

    public static WebDriver driver;
    public Selenium selenium;
    public WebDriverWait wait;
    public String propertyFile;
    String getSessionId;


    public demo() { // constructor


        DesiredCapabilities ieCapabilities = DesiredCapabilities
                .internetExplorer();
        ieCapabilities
                .setCapability(
                        InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
                        true);
        driver = new InternetExplorerDriver(ieCapabilities);


        this.saveSessionIdToSomeStorage(getSessionId);
        this.startSession(ieCapabilities);
        driver.manage().window().maximize();
    }

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

    private void saveSessionIdToSomeStorage(String session) {
        session=((RemoteWebDriver) driver).getSessionId().toString();
    }

    private String getPreviousSessionIdFromSomeStorage() {
        return getSessionId;
    }
}

我希望通过重写remoteWebdriver中的startSession()方法,它会以某种方式检查我是否已经在中打开了webdriver浏览器的一个实例,并且它将使用该实例,而不是每次我在eclipse中点击“运行”按钮时都重新创建一个新实例

我还可以看到,因为我正在从构造函数创建一个“新的驱动程序实例”,因为构造函数总是先执行,它会自动创建新的驱动程序实例,所以我可能需要以某种方式更改它,但不知道如何更改。

public class demo extends RemoteWebDriver { 

    public static WebDriver driver;
    public Selenium selenium;
    public WebDriverWait wait;
    public String propertyFile;
    String getSessionId;


    public demo() { // constructor


        DesiredCapabilities ieCapabilities = DesiredCapabilities
                .internetExplorer();
        ieCapabilities
                .setCapability(
                        InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
                        true);
        driver = new InternetExplorerDriver(ieCapabilities);


        this.saveSessionIdToSomeStorage(getSessionId);
        this.startSession(ieCapabilities);
        driver.manage().window().maximize();
    }

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

    private void saveSessionIdToSomeStorage(String session) {
        session=((RemoteWebDriver) driver).getSessionId().toString();
    }

    private String getPreviousSessionIdFromSomeStorage() {
        return getSessionId;
    }
}
我是stackoverflow和SeleniumWebDriver的新手,希望这里有人能帮我


谢谢

要回答您的问题:

不可以。您不能使用当前正在计算机上运行的浏览器。但是,您可以对不同的测试使用相同的浏览器,只要它处于相同的执行状态


然而,听起来你真正的问题是一遍又一遍地运行100个测试。我建议使用测试框架(如TestNG或JUnit)。通过这些,您可以指定要运行的测试(TestNG将生成所有失败测试的XML文件,因此,当您运行它时,它将只执行失败的测试)。

要回答您的问题:

不可以。您不能使用当前正在计算机上运行的浏览器。但是,您可以对不同的测试使用相同的浏览器,只要它处于相同的执行状态


然而,听起来你真正的问题是一遍又一遍地运行100个测试。我建议使用测试框架(如TestNG或JUnit)。通过这些,您可以指定要运行的测试(TestNG将生成所有失败测试的XML文件,因此,当您运行它时,它将只执行失败的测试)。

实际上,您可以再次使用相同的会话

在节点客户端中,您可以使用以下代码附加到现有的selenium会话

var browser = wd.remote('http://localhost:4444/wd/hub');
browser.attach('df606fdd-f4b7-4651-aaba-fe37a39c86e3', function(err, capabilities) {
  // The 'capabilities' object as returned by sessionCapabilities
  if (err) { /* that session doesn't exist */ }
  else {
    browser.elementByCss("button.groovy-button", function(err, el) {
      ...
    });
  }
});
...
browser.detach();
要获取selenium会话id

driver.getSessionId();
注: 这仅在节点客户端中可用。。
要在JAVA或C#中执行同样的操作,您必须重写selenium的execute方法来捕获sessionId并将其保存在本地文件中,然后再次读取它以附加到现有的selenium会话中

实际上,您可以再次使用相同的会话

var browser = wd.remote('http://localhost:4444/wd/hub');
browser.attach('df606fdd-f4b7-4651-aaba-fe37a39c86e3', function(err, capabilities) {
  // The 'capabilities' object as returned by sessionCapabilities
  if (err) { /* that session doesn't exist */ }
  else {
    browser.elementByCss("button.groovy-button", function(err, el) {
      ...
    });
  }
});
...
browser.detach();
在节点客户端中,您可以使用以下代码附加到现有的selenium会话

var browser = wd.remote('http://localhost:4444/wd/hub');
browser.attach('df606fdd-f4b7-4651-aaba-fe37a39c86e3', function(err, capabilities) {
  // The 'capabilities' object as returned by sessionCapabilities
  if (err) { /* that session doesn't exist */ }
  else {
    browser.elementByCss("button.groovy-button", function(err, el) {
      ...
    });
  }
});
...
browser.detach();
要获取selenium会话id

driver.getSessionId();
注: 这仅在节点客户端中可用。。
要在JAVA或C#中执行相同的操作,您必须重写selenium的execute方法来捕获sessionId并将其保存在本地文件中,然后再次读取它以附加到现有的selenium会话中

我尝试了以下步骤来使用相同的浏览器实例,它对我有效:

var browser = wd.remote('http://localhost:4444/wd/hub');
browser.attach('df606fdd-f4b7-4651-aaba-fe37a39c86e3', function(err, capabilities) {
  // The 'capabilities' object as returned by sessionCapabilities
  if (err) { /* that session doesn't exist */ }
  else {
    browser.elementByCss("button.groovy-button", function(err, el) {
      ...
    });
  }
});
...
browser.detach();
如果您在不同的包中使用泛型或类1,那么下面的代码段将起作用-

package zgenerics;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
//第1类:

public class Generics  {

public Generics(){}

protected WebDriver driver;

@BeforeTest

public void maxmen() throws InterruptedException, IOException{ 
driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
    String appURL= "url";
    driver.get(appURL);
    String expectedTitle = "Title";
    String actualTitle= driver.getTitle();
    if(actualTitle.equals(expectedTitle)){
        System.out.println("Verification passed");
    }
    else {
        System.out.println("Verification failed");
    } }
//第2类:

package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import zgenerics.Generics;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class Login extends Generics {
@Test
public void Login() throws InterruptedException, Exception {
WebDriverWait wait = new WebDriverWait(driver,25);

   wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("")));
   driver.findElement(By.cssSelector("")).sendKeys("");

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("")));
    driver.findElement(By.xpath("")).sendKeys("");

}
}
如果泛型类在同一个包中,则只需对代码进行以下更改:

public class Generics  {

public Generics(){}

WebDriver driver; }
只需从Webdriver代码行中删除受保护的字。类1的Rest代码保持原样

问候,,
Mohit Baluja

我尝试了以下步骤来使用相同的浏览器实例,它对我有效:

如果您在不同的包中使用泛型或类1,那么下面的代码段将起作用-

package zgenerics;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;
//第1类:

public class Generics  {

public Generics(){}

protected WebDriver driver;

@BeforeTest

public void maxmen() throws InterruptedException, IOException{ 
driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
    String appURL= "url";
    driver.get(appURL);
    String expectedTitle = "Title";
    String actualTitle= driver.getTitle();
    if(actualTitle.equals(expectedTitle)){
        System.out.println("Verification passed");
    }
    else {
        System.out.println("Verification failed");
    } }
//第2类:

package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import zgenerics.Generics;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class Login extends Generics {
@Test
public void Login() throws InterruptedException, Exception {
WebDriverWait wait = new WebDriverWait(driver,25);

   wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("")));
   driver.findElement(By.cssSelector("")).sendKeys("");

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("")));
    driver.findElement(By.xpath("")).sendKeys("");

}
}
如果泛型类在同一个包中,则只需对代码进行以下更改:

public class Generics  {

public Generics(){}

WebDriver driver; }
只需从Webdriver代码行中删除受保护的字。类1的Rest代码保持原样

问候,,
Mohit Baluja

我通过扩展类(Java继承)和创建xml文件来尝试它。我希望下面的例子能有所帮助:

第1类:

public class Generics  {

public Generics(){}

protected WebDriver driver;

@BeforeTest

public void maxmen() throws InterruptedException, IOException{ 
driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
    String appURL= "url";
    driver.get(appURL);
    String expectedTitle = "Title";
    String actualTitle= driver.getTitle();
    if(actualTitle.equals(expectedTitle)){
        System.out.println("Verification passed");
    }
    else {
        System.out.println("Verification failed");
    } }
 package zgenerics;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;

public class SetUp  {

public Generics(){}
protected WebDriver driver;

@BeforeTest
public void maxmen() throws InterruptedException, IOException{
    driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
    String appURL= "URL";

    driver.get(appURL);

    String expectedTitle = "Title";

    String actualTitle= driver.getTitle();

    if(actualTitle.equals(expectedTitle)){
        System.out.println("Verification passed");
    }
    else {
        System.out.println("Verification failed");
    } }
第2类:

package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import zgenerics.Generics;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class Login extends Generics {
@Test
public void Login() throws InterruptedException, Exception {
WebDriverWait wait = new WebDriverWait(driver,25);

   wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("")));
   driver.findElement(By.cssSelector("")).sendKeys("");

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("")));
    driver.findElement(By.xpath("")).sendKeys("");

}
}
 package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import zgenerics.SetUp

 public class Conditions extends SetUp {

@Test
public void visible() throws InterruptedException{

    Thread.sleep(5000);
    boolean signINbutton=driver.findElement(By.xpath("xpath")).isEnabled();
    System.out.println(signINbutton);

    boolean SIGNTEXT=driver.findElement(By.xpath("xpath")).isDisplayed();
    System.out.println(SIGNTEXT);

    if (signINbutton==true && SIGNTEXT==true){
        System.out.println("Text and button is present");
           }
    else{
        System.out.println("Nothing is visible");
        }
       }
       }
第3类:

    package automationScripts;
    import java.io.IOException;
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebElement;
    import org.testng.annotations.Test;

public class Footer extends Conditions {

  @Test
  public void footerNew () throws InterruptedException{

    WebElement aboutUs = driver.findElement(By.cssSelector("CssSelector"));
    aboutUs.click();


    WebElement cancel = driver.findElement(By.xpath("xpath"));
    cancel.click();

    Thread.sleep(1000);

    WebElement TermsNCond = driver.findElement(By.xpath("xpath"));
    TermsNCond.click();
    }   
    }
现在使用以下代码创建一个xml文件,例如,并以testng套件的形式运行testng.xml: 复制并粘贴下面的代码,并相应地进行编辑

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" parallel="classes" thread-count="3">
<test name="PackTest">
<classes>
   <class name="automationScripts.Footer"/>
</classes>

这将运行三个以上的类。这意味着一个浏览器和不同的测试。
我们可以通过按字母顺序设置类名来设置执行顺序,就像我在上面的类中所做的那样。

我通过扩展类(Java继承)和创建xml文件来尝试。我希望下面的例子能有所帮助:

第1类:

public class Generics  {

public Generics(){}

protected WebDriver driver;

@BeforeTest

public void maxmen() throws InterruptedException, IOException{ 
driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
    String appURL= "url";
    driver.get(appURL);
    String expectedTitle = "Title";
    String actualTitle= driver.getTitle();
    if(actualTitle.equals(expectedTitle)){
        System.out.println("Verification passed");
    }
    else {
        System.out.println("Verification failed");
    } }
 package zgenerics;

import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.openqa.selenium.WebDriver;

public class SetUp  {

public Generics(){}
protected WebDriver driver;

@BeforeTest
public void maxmen() throws InterruptedException, IOException{
    driver = new FirefoxDriver();
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); 
    String appURL= "URL";

    driver.get(appURL);

    String expectedTitle = "Title";

    String actualTitle= driver.getTitle();

    if(actualTitle.equals(expectedTitle)){
        System.out.println("Verification passed");
    }
    else {
        System.out.println("Verification failed");
    } }
第2类:

package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import zgenerics.Generics;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class Login extends Generics {
@Test
public void Login() throws InterruptedException, Exception {
WebDriverWait wait = new WebDriverWait(driver,25);

   wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("")));
   driver.findElement(By.cssSelector("")).sendKeys("");

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("")));
    driver.findElement(By.xpath("")).sendKeys("");

}
}
 package automationScripts;
import org.openqa.selenium.By;
import org.testng.annotations.Test;
import zgenerics.SetUp

 public class Conditions extends SetUp {

@Test
public void visible() throws InterruptedException{

    Thread.sleep(5000);
    boolean signINbutton=driver.findElement(By.xpath("xpath")).isEnabled();
    System.out.println(signINbutton);

    boolean SIGNTEXT=driver.findElement(By.xpath("xpath")).isDisplayed();
    System.out.println(SIGNTEXT);

    if (signINbutton==true && SIGNTEXT==true){
        System.out.println("Text and button is present");
           }
    else{
        System.out.println("Nothing is visible");
        }
       }
       }
第3类:

    package automationScripts;
    import java.io.IOException;
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebElement;
    import org.testng.annotations.Test;

public class Footer extends Conditions {

  @Test
  public void footerNew () throws InterruptedException{

    WebElement aboutUs = driver.findElement(By.cssSelector("CssSelector"));
    aboutUs.click();


    WebElement cancel = driver.findElement(By.xpath("xpath"));
    cancel.click();

    Thread.sleep(1000);

    WebElement TermsNCond = driver.findElement(By.xpath("xpath"));
    TermsNCond.click();
    }   
    }
现在使用以下代码创建一个xml文件,例如,并以testng套件的形式运行testng.xml: 复制并粘贴下面的代码,并相应地进行编辑

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="TestSuite" parallel="classes" thread-count="3">
<test name="PackTest">
<classes>
   <class name="automationScripts.Footer"/>
</classes>

这将运行三个以上的类。这意味着一个浏览器和不同的测试。 我们可以通过按字母顺序设置类名来设置执行顺序,就像我在中所做的那样