在本节中, 你将学习如何创建你的First Selenium Automation测试脚本。
在此测试下, 我们将自动执行以下方案:
- 调用Google Chrome浏览器。
- 公开网址:www.google.com
- 点击Google搜索文本框。
- 输入值” srcmini tutorials”
- 点击搜索按钮。
我们将逐步创建测试用例, 以使你详细了解每个组件。
步骤1。启动Eclipse IDE, 并打开在本教程的上一节(配置Selenium WebDriver)中创建的项目” Demo_Test”。我们将在” Demo_Test”测试套件下的” First.class”文件中编写第一个Selenium测试脚本。

注意:要在Selenium中调用浏览器, 我们必须下载特定于该浏览器的可执行文件。例如, Chrome浏览器使用名为ChromeDriver.exe的可执行文件来实现WebDriver协议。这些可执行文件将启动系统上的服务器, 该服务器负责在Selenium中运行测试脚本。
第2步。在浏览器中打开网址:https://sites.google.com/a/chromium.org/chromedriver/downloads。
第三步点击” ChromeDriver 2.41″链接。它将你重定向到ChromeDriver可执行文件的目录。根据你当前使用的操作系统下载。

对于Windows, 单击” chromedriver_win32.zip”下载。

下载的文件将是压缩格式。将内容解压缩到方便的目录中。

注意:Selenium开发人员已经为每个浏览器定义了属性, 这些属性需要解析各个可执行文件的位置才能调用浏览器。例如, 为Chrome浏览器定义的属性webdriver.chrome.driver需要其可执行文件的路径D:\ ChromeDriver \ chromedriver.exe才能启动chrome浏览器。

步骤4。我们需要对Web元素(例如Google搜索文本框和搜索按钮)进行唯一标识, 以便通过我们的测试脚本将它们自动化。这些唯一的标识与一些命令/语法一起配置以形成定位符。定位器帮助我们在Web应用程序的上下文中定位和标识特定的Web元素。
查找唯一标识元素的方法涉及检查HTML代码。
- 在你的Chrome浏览器中打开网址:https://www.google.com。
- 右键点击Google搜索文本框, 然后选择检查元素。

- 它将启动一个窗口, 其中包含测试盒开发中涉及的所有特定代码。

- 选择id元素的值, 即” lst-ib”。

- 下面给出的是Java语法, 用于通过Selenium WebDriver中的” id”来定位元素。
- 这是在我们的测试脚本中查找Google搜索文本框的完整代码。
- 现在, 右键单击Google搜索按钮, 然后选择检查元素。

- 它将启动一个窗口, 其中包含开发Google搜索按钮所涉及的所有特定代码。

- 选择名称元素的值, 即” btnK”。

- 下面给出的Java语法用于通过Selenium WebDriver中的”名称”来定位元素。
- 这是在我们的测试脚本中查找Google搜索按钮的完整代码。
第五步现在该进行编码了。我们为每个代码块都嵌入了注释, 以清楚地说明这些步骤。
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class First {
public static void main(String[] args) {
// declaration and instantiation of objects/variables
System.setProperty("webdriver.chrome.driver", "D:\\ChromeDriver\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
// Launch website
driver.navigate().to("http://www.google.com/");
// Click on the search text box and send value
driver.findElement(By.id("lst-ib")).sendKeys("srcmini tutorials");
// Click on the search button
driver.findElement(By.name("btnK")).click();
}
}
Eclipse代码窗口将如下所示:

第六步右键单击Eclipse代码, 然后选择运行方式> Java应用程序。

第七步以上测试脚本的输出将显示在Google Chrome浏览器中。

代码说明
进口包装/声明
在Java中, import语句用于导入另一个包中存在的类。简而言之, import关键字用于将内置和用户定义的包导入到Java源文件中。
- org.openqa.selenium.WebDriver-引用实例化新的Web浏览器所需的WebDriver接口。
- org.openqa.selenium.chrome.ChromeDriver-引用将Chrome特定的驱动程序实例化到由WebDriver类实例化的浏览器上所需的ChromeDriver类。
实例化对象和变量
通过以下方式实例化驱动程序对象:
WebDriver driver=new ChromeDriver();
启动网站
要启动新网站, 我们使用WebDriver中的navigation()。to()方法。
driver.navigate().to("http://www.google.com/");
点击一个元素
在WebDriver中, 用户交互是通过使用定位器执行的, 我们将在本教程的后续课程中进行讨论。目前, 以下代码实例用于在特定的Web元素中定位和解析值。
driver.findElement(By.id("lst-ib")).sendKeys("srcmini tutorials");