Selenium 简明教程

Selenium Webdriver - Driver Sessions

Webdriver 会话通常指浏览器的启动和关闭。通过初始化驱动程序类对象默认创建会话。有两种类型的驱动程序类 - 本地驱动程序和远程驱动程序。

The webdriver sessions mostly refer to the beginning and closing of the browser. A session is created by default by initializing the driver class object. There are two types of driver class - Local Driver and Remote Driver.

若要退出驱动程序,请使用 quit() 方法。始终建议使用 quit() 而非 close(),因为 close() 方法只能关闭聚焦的浏览器,而会话 ID 将返回无效或已过期,而 quit() 方法会终止驱动程序会话,且会话 ID 将返回为 null。

For quitting the driver, the quit() method is used. It is always recommended to use the quit() instead of close(), because close() method can only close the browser in focus and the session id will be returned as invalid or expired, while the quit() method terminates the driver session, and the session id will be returned as null.

Session Handling with Selenium Webdriver

我们可以借助 Selenium webdriver 使用 TestNG 框架执行会话处理。若要触发不同的会话,应在 TestNG XML 文件中使用 parallel 属性。

We can perform session handling with the help of Selenium webdriver using the TestNG framework. To trigger different sessions, we shall use the attribute parallel in the TestNG XML file.

TestNG 执行配置在 TestNG XML 中进行。要创建多个会话,我们需要将属性 parallel 和 thread-count 添加到 XML 文件中。

A TestNG execution configuration is done in the TestNG XML. To create multiple sessions, we shall add the attributes – parallel and thread-count in the XML file.

属性 thread-count 控制在并行模式下执行测试时要创建的会话数。parallel 属性的值设置为 methods。

The attribute thread-count controls the number of sessions to be created while executing the tests in a parallel mode. The value of the parallel attribute is set to methods.

Get Session IDS In Selenium Webdriver

要获取多个会话 id,我们将创建三个方法,这些方法将并行进行。我们将使用 RemoteWebDriver 类在该测试中获取不同的会话 id。

To get multiple session ids, we would create three methods which will in parallel. We would get the different session ids in this test using the RemoteWebdriver class.

RemoteWebDriver 是一个实现了 WebDriver 接口的类。RemoteWebDriver 被广泛用于在远程计算机中触发执行。会话 id 是分配给每个会话的唯一编号。它的格式为 UUID。

A RemoteWebdriver is a class which implements the webdriver interface. The RemoteWebdriver is used widely to trigger execution in the remote machines. A session id is a distinct number assigned to each session. It has a format in UUID.

Example - Get Session IDS

SessionHandling.java 中的代码实现

Code Implementation in SessionHandling.java

package Report;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.remote.SessionId;
import org.testng.annotations.*;
import org.openqa.selenium.remote.RemoteWebDriver;

public class SessionHandling {
   WebDriver driver;
   @Test
   public void method1() {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      //launch URL
      driver.get("https://www.tutorialspoint.com/selenium/practice/browser-windows.php");

      //get session ID
      SessionId s = ((RemoteWebDriver)driver).getSessionId();
      System.out.println("Session Id is for method1: " + s);
   }
   @Test
   public void method2() {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      //launch URL
      driver.get("https://www.tutorialspoint.com/selenium/practice/login.php");

      //get session ID
      SessionId s = ((RemoteWebDriver)driver).getSessionId();
      System.out.println("Session Id is for method2: " + s);
   }
   @Test
   public void method3() {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      //launch URL
      driver.get("https://www.tutorialspoint.com/selenium/practice/accordion.php");

      //get session ID
      SessionId s = ((RemoteWebDriver)driver).getSessionId();
      System.out.println("Session Id is for method3: " + s);
   }
}

testng.xml 文件中的配置。

Configurations in testng.xml file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="All Test Suite" parallel="methods" thread-count="3">
   <test verbose="2" preserve-order="true" name="TestNGTest.java">
      <classes>
         <class name="Report.SessionHandling"></class>
      </classes>
   </test>
</suite>

pom.xml 文件中的依赖项。

Dependencies in pom.xml file.

<?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.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>

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

      <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
      <dependency>
         <groupId>org.testng</groupId>
         <artifactId>testng</artifactId>
         <version>7.9.0</version>
         <scope>test</scope>
      </dependency>
   </dependencies>
</project>

上述实现的项目结构如下图所示 −

Project structure of the above implementation is shown in the below image −

selenium driver sessions
Session Id is for method1: 63eae5bba42f97e30e7d01ef211f51e9
Session Id is for method2: 0b23f13aee68ca7c92de1cd93ee78c93
Session Id is for method3: e06fdaa8de91f4706e81566c854d1cf1

===============================================
Default Suite
Total tests run: 3, Passes: 3, Failures: 0, Skips: 0
===============================================

Process finished with exit code 0

控制台中显示的结果为 Total tests run: 3 ,因为存在三个具有 @Test 注释的方法 - method1()、method2() 和 method3()。此外,我们已使用控制台中的消息 Session Id is for method1: 63eae5bba42f97e30e7d01ef211f51e9, Session Id is for method2: 0b23f13aee68ca7c92de1cd93ee78c93Session Id is for method3: e06fdaa8de91f4706e81566c854d1cf1 获得了并行运行的三个方法的会话 id。

The result in the console shows Total tests run: 3, as there were three methods with @Test annotations - method1(), method2(), and method3(). Also, we had obtained the session ids of the three methods running in the parallel with the messages in console - Session Id is for method1: 63eae5bba42f97e30e7d01ef211f51e9, Session Id is for method2: 0b23f13aee68ca7c92de1cd93ee78c93, and Session Id is for method3: e06fdaa8de91f4706e81566c854d1cf1.

最后,接收到消息 Passes: 3Process finished with exit code 0 ,表示代码执行成功。

Finally, the message Passes: 3, and Process finished with exit code 0 was received, signifying successful execution of the code.

以下链接提供了关于 TestNG 的详细说明 −

The below link provides a detailed description of TestNG −

Get Single Session ID in Selenium WebDriver

要获取单个会话 id,我们将使用 RemoteWebDriver 类打开一个会话。每个会话都有一个唯一的会话 id。RemoteWebDriver 是一个实现了 WebDriver 接口的类。RemoteWebDriver 被广泛用于在远程计算机中触发执行。

To get a single session id, we would open a session using the RemoteWebdriver class. A session id is unique to every session. A RemoteWebdriver is a class which implements the webdriver interface. The RemoteWebdriver is used widely to trigger execution in the remote machines.

Example - Get Single ID

HandlingSessionID.java 中的代码实现

Code Implementation in HandlingSessionID.java

package org.example;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;

public class HandlingSessionID {
   public static void main(String[] args) throws InterruptedException {

      // Initiate the Webdriver
      WebDriver driver = new ChromeDriver();

      // adding implicit wait of 15 secs
      driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

      // Opening the webpage where we will get the session id
      driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");

      //get webdriver session id
      SessionId s = ((RemoteWebDriver) driver).getSessionId();
      System.out.println("Session Id is: " + s);

      // Closing browser
      driver.quit();
   }
}

pom.xml 文件中的依赖项。

Dependencies in pom.xml file.

<?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.example</groupId>
   <artifactId>SeleniumJava</artifactId>
   <version>1.0-SNAPSHOT</version>

   <properties>
      <maven.compiler.source>16</maven.compiler.source>
      <maven.compiler.target>16</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
   </properties>

   <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->
   <dependencies>
      <dependency>
         <groupId>org.seleniumhq.selenium</groupId>
         <artifactId>selenium-java</artifactId>
         <version>4.11.0</version>
      </dependency>
   </dependencies>
</project>
Session Id is: 78eae5bba42f97e30e7d01ef234f51e9

Process finished with exit code 0

在上述示例中,我们已使用控制台中的消息 Session Id is: 78eae5bba42f97e30e7d01ef234f51e9 获得了 WebDriver 的会话 id。

In the above example, we had obtained the session id of webdriver with the message in the console - Session Id is: 78eae5bba42f97e30e7d01ef234f51e9.

最后,收到了消息 Process finished with exit code 0 ,表示代码成功执行。

Finally, the message Process finished with exit code 0 was received, signifying successful execution of the code.

这总结了我们对 Selenium WebDriver - 驱动程序会话教程的全面理解。我们已首先介绍了 WebDriver 会话、close() 和 quit() 方法之间的差异,并通过一个示例展示了如何使用 Selenium 获取会话 id。

This concludes our comprehensive take on the tutorial on Selenium Webdriver - Driver Sessions. We’ve started with describing a webdriver session, differences between close() and quit() methods, and walked through an example illustrating how to get the session ids with Selenium.

这为您提供了对 Selenium WebDriver - 驱动程序会话的深入了解。您最好继续实践所学知识并探索其他与 Selenium 相关的知识,以加深理解并拓宽视野。

This equips you with in-depth knowledge of the Selenium webdriver - driver sessions. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.