Selenium 简介
环境配置
- 安装JDK, 建议使用JDK1.8, 可以参照官网安装
- 安装eclipse
- 下载ChromeDriver:https://chromedriver.storage.googleapis.com/index.html, 根据自己的Chrome版本下载指定版本的driver
- 下载完成后将driver的路径放在path环境变量里
- 新建Maven项目,POM文件如下,注意Dependencies部分。
<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>com.stone.demos</groupId>
<artifactId>SeleniumDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SeleniumDemo</name>
<description>A demo project for Selenium</description>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
</dependencies>
</project>
代码展示
package com.stone.demos.seleniumdemo;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import static org.openqa.selenium.support.ui.ExpectedConditions.*;
public class Demo {
public static void main(String[] args) {
WebDriver chrome = new ChromeDriver();
WebDriverWait wait = new WebDriverWait(chrome, 30);
try {
chrome.get("https://www.sogou.com");
WebElement searchTextBox = wait.until(presenceOfElementLocated(By.cssSelector(".sec-input")));
WebElement searchButton = wait.until(presenceOfElementLocated(By.cssSelector("#stb")));
searchTextBox.clear();
searchTextBox.sendKeys("CSDN");
searchButton.click();
WebElement theFirstLink = wait.until(presenceOfElementLocated(By.xpath("(//h3[@class='vrTitle'])[1]/a")));
theFirstLink.click();
assert chrome.getTitle().equalsIgnoreCase("CSDN-专业IT技术社区");
}finally {
chrome.quit();
}
}
}
代码讲解
- WebDriver chrome = new ChromeDriver(); 启动Chrome浏览器
- chrome.get(“https://www.sogou.com”); 访问搜狗网站
- 搜索“CSDN” searchTextBox.sendKeys(“CSDN”);
- 点击打开第一个搜索结果:theFirstLink.click();
- 验证站点的台头是“CSDN-专业IT技术社区”: assert chrome.getTitle().equalsIgnoreCase(“CSDN-专业IT技术社区”);
- 最后关闭浏览器