Selenium 简明教程

Selenium with Java Tutorial

Selenium 用于自动化测试用例开发,用于测试基于网络的应用程序。它支持多于一种的编程语言,如 Java、 PythonC# 等。

Selenium is used for automating test cases developed to test web based application. It supports more than one programming languages like Java, Python, C#, and so on.

How to Setup Selenium with Java?

Step 1 − 从链接 Java Downloads 下载和安装 Java。

Step 1 − Download and install Java from the link Java Downloads.

若要详细了解如何设置 Java,请参阅链接 Java Environment Setup

To get a more detailed view on how set up Java, refer to the link Java Environment Setup.

一旦成功安装 Java,我们可通过从命令提示符运行命令 java 来确认其安装。

Once we have successfully installed Java, we can confirm its installation by running the command: java, from the command prompt.

C:\java

Step 2 − 接下来,我们要通过运行命令 java –version 来确认所安装 Java 的版本。

Step 2 − Next, we would Confirm the version of the Java installed by running the command: java –version.

java –version

它将显示以下输出 −

It will show the following output −

openjdk version "17.0.9" 2023-10-17
OpenJDK Runtime Environment Homebrew (build 17.0.9+0)
OpenJDK 64-Bit Server VM Homebrew (build 17.0.9+0, mixed mode, sharing)

Step 3 − 使用链接 Downloading Apache Maven 在我们的系统中安装 Maven。

Step 3 − Install Maven in our system using the link Downloading Apache Maven.

接下来,我们要通过运行以下命令来确认所安装的 Maven 版本−

Next, we would confirm the version of the Maven installed by running the following command −

通过运行命令确认所安装 Maven 的版本: mvn –version

Confirm the version of the Maven installed by running the command: mvn –version.

mvn –version.

它将显示以下输出 −

It will show the following output −

Apache Maven 3.9.6 (bc0240f3c744dd6b6ec2920b3cd08dcc295161ae)
Maven home: /opt/homebrew/Cellar/maven/3.9.6/libexec
Java version: 21.0.1, vendor: Homebrew, runtime: /opt/homebrew/Cellar/openjdk/21.0.1/libexec/openjdk.jdk/Contents/Home
Default locale: en_IN, platform encoding: UTF-8
OS name: "mac os x", version: "14.0", arch: "aarch64", family: "mac"

所执行命令的输出表示系统中所安装的 Maven 版本是 Apache Maven 3.9.6。

The output of the command executed signified that the Maven version installed in the system is Apache Maven 3.9.6.

Step 4 − 安装名为 IntelliJ 的代码编辑器来编写和运行 Selenium 测试。

Step 4 − Install a code editor called the IntelliJ to write and run the Selenium test.

Step 5 − 将以下代码添加到 Main.java 文件中。

Step 5 − Add the below code in the Main.java file.

package org.example;

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

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

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

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

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

      // get browser title after browser launch
      System.out.println("Browser title: " + driver.getTitle());
   }
}

在 pom.xml 文件中添加的总依赖项−

Overall dependencies added in the 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.19.0</version>
      </dependency>
   </dependencies>
</project>

Step 6 − 右键单击并选择“运行‘Main.main()’ 选项”。等到运行完成后。

Step 6 − Right click and select Run ‘Main.main()’ option. Wait till the run is completed.

Step 7 − 应启动 Chrome 浏览器,输出控制台消息应为 - *浏览器标题:Selenium Practice - Resizeabl*e。

Step 7 − Chrome browser should be launched, the output in console with the message should be - *Browser Title: Selenium Practice - Resizeabl*e.

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

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

同时启动 Chrome 浏览器,并顶部显示了消息 Chrome is being controlled by automated test software

Along with that Chrome browser got launched with the message Chrome is being controlled by automated test software at the top.

Launch Browser and Quit Driver with Selenium Java

我们可以启动浏览器并使用 driver.get() 方法打开一个应用程序,最后使用 close() 方法关闭浏览器。

We can launch the browser and open an application using the driver.get() method, and finally close the browser with the close() method.

package org.example;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import java.util.concurrent.TimeUnit;

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

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

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

      // URL launch and get the browser title
      driver.get("https://www.tutorialspoint.com/selenium/practice/droppable.php");
      System.out.println( "Browser title obtained : " + driver.getTitle());

      // close browser
      driver.close();
   }
}

它将显示以下输出 −

It will show the following output −

Browser title obtained: Browser Title: Selenium Practice - Droppable

Process finished with exit code 0

在上例中,我们首先启动 Chrome 浏览器,然后获取浏览器标题,再关闭浏览器,并在控制台接收到消息- Browser title obtained: Selenium Practice - Student Registration Form

In the above example, we had first launched the Chrome browser then obtained the browser title and, then closed the browser, and in the console received the message - Browser title obtained: Selenium Practice - Student Registration Form.

How to Identify an Element and Check its Functionality using Selenium Java?

当启动应用程序时,用户与页面上的网络元素进行交互,例如点击链接或按钮,在输入框中输入文本,等等,以创建自动化测试用例。

As an application is launched, the users interact with the web elements on the page like click on a link or a button, enter text within an input box, and so on to create the automation test cases.

第一个任务是定位元素。在 Selenium 中有 locators 可用,即 id、class、class name、name、link text、partial link text、tagname、css 和 xpath。它们在 Java 中与 findElement() 方法一起使用。

The first task is to locate the element. There are multiple locators available in Selenium namely the id, class, class name, name, link text, partial link text, tagname, css, and xpath. They ate used along with the findElement() method in Java.

例如,findElement(By.name(“name”)) 将识别具有 name 属性值第一个网络元素。如果具有相同 name 属性值的元素为零,则应抛出 NoSuchElementException

For instance, findElement(By.name(“name”)) will identify the first web element with the name attribute value. In case there is zero element with the same value of the name attribute, NoSuchElementException should be thrown

让我们看看以下图片中突出显示的相同输入框的 html 代码 −

Let us see the html code of the same input box as highlighted in the below image −

selenium java tutorial 2
<input name="name" id="name" type="text" class="form-control" placeholder="First Name">

上图中突出显示的编辑框具有值为 name 的 name 属性。在识别出该编辑框后,让我们将文本 Selenium 输入到该编辑框中。

The edit box highlighted in the above image has a name attribute with a value as name. Let us input the text Selenium into this edit box after identifying it.

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 LocatorsName {
   public static void main(String[] args) throws InterruptedException {

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

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

      // Opening the webpage where we will identify edit box enter text
      driver.get("https://www.tutorialspoint.com/selenium/practice/selenium_automation_practice.php");

      // Identify the search box with name locator to enter text
      WebElement i = driver.findElement(By.name("name"));
      i.sendKeys("Selenium");

      // Get the value entered
      String text = i.getAttribute("value");
      System.out.println("Entered text is: " + text);

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

它将显示以下输出 −

It will show the following output −

Entered text is: Selenium

Process finished with exit code 0

输出显示消息 - Process with exit code 0 ,表示上述代码已成功执行。此外,在输入框内输入的值(从 getAttribute 方法获取) - Selenium 已打印在控制台中。

The output shows the message - Process with exit code 0 meaning that the above code executed successfully. Also, the value entered within the edit box (obtained from the getAttribute method) - Selenium got printed in the console.

Conclusion

这结束了我们对 Selenium Java 教程教程的全面了解。我们从如何使用 Java 设置 Selenium、如何使用 Selenium Java 启动浏览器和退出会话以及如何使用 Selenium Java 识别元素并检查其功能开始。这使你对 Selenium Java 教程有了深入的了解。明智的做法是不断练习你所学到的内容,并探索其他与 Selenium 相关的内容,以加深理解并拓宽视野。

This concludes our comprehensive take on the tutorial on Selenium Java Tutorial. We’ve started with describing how to set up Selenium with Java, how to launch a browser and quit a session using the Selenium Java, and how to identify an element and check its functionality using Selenium Java. This equips you with in-depth knowledge of the Selenium Java Tutorial. It is wise to keep practicing what you’ve learned and exploring others relevant to Selenium to deepen your understanding and expand your horizons.