Selenium是一个用于测试网站的自动化测试工具,支持各种浏览器包括Chrome、Firefox、Safari等主流界面浏览器,同时也支持phantomJS无界面浏览器。
查看chrome版本,114.05735.199
去 http://chromedriver.storage.googleapis.com/index.html 网站下载对应版本的驱动
禁止Chrome自动更新
服务:Goggle更新服务改为禁用
google浏览器图标右键,属性,目标栏后添加:--disable-background-networking
Selenium常用API--Java语言
环境配置、浏览器驱动、selenium元素定位、浏览器操作、模拟鼠标/键盘操作、获取断言信息、设置元素等待、定位一组元素、多表单切换、多窗口切换、浏览器cookie操作、调用JavaScript代码、获取窗口截图等。
maven依赖
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<!-- 目前来说就3.141.59这个版本好使高版本会有问题-->
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>22.0</version>
</dependency>
工具类
ChromeDriverUtil.java
package com.selenium.auto.seleniumjava.util;
import lombok.SneakyThrows;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class ChromeDriverUtil {
//文件版本,防止多线程缓存文件和用户文件共享,导致创建错误
private static AtomicInteger fileSerial = new AtomicInteger(0);
private ChromeDriver driver;
public ChromeDriverUtil(String path, boolean pd, boolean img) {
init(path, pd, img);
}
@SneakyThrows
private void init(String path, boolean pd, boolean img) {
System.setProperty("webdriver.chrome.driver", path);
ChromeOptions options = new ChromeOptions();
if (!pd) {
options.addArguments("--headless"); //无浏览器模式
}
options.addArguments("--disable-gpu"); // 谷歌文档提到需要加上这个属性来规避bug
options.addArguments("--disable-software-rasterizer"); //禁用3D软件光栅化器
options.addArguments("--no-sandbox");// 为了让linux root用户也能执行
// 优化参数
options.addArguments("--disable-dev-shm-usage"); //解决在某些VM环境中,/dev/shm分区太小,导致Chrome失败或崩溃
if (img) {
options.addArguments("blink-settings=imagesEnabled=false"); //禁止加图片,如果爬取图片的话,这个不能禁用
options.addArguments("--disable-images");
}
String tmpdir = System.getProperty("java.io.tmpdir");
String dir = tmpdir + File.separator + "chrome_file_data_cache" + File.separator + fileSerial.incrementAndGet();
File file1 = new File(dir + File.separator + "data");
if (file1.exists()) {
file1.mkdirs();
}
File file2 = new File(dir + File.separator + "cache");
if (file2.exists()) {
file1.mkdirs();
}
options.addArguments("--user-data-dir=" + file1.getAbsolutePath()); //解决打开页面出现data;空白页面情况,因为没有缓存目录
options.addArguments("--disk-cache-dir=" + file2.getAbsolutePath()); //指定Cache路径
options.addArguments("--incognito"); //无痕模式
options.addArguments("--disable-plugins"); //禁用插件,加快速度
options.addArguments("--disable-extensions"); //禁用扩展
options.addArguments("--disable-popup-blocking"); //关闭弹窗拦截
options.addArguments("--ignore-certificate-errors"); // 禁现窗口最大化
options.addArguments("--allow-running-insecure-content"); //关闭https提示 32位
options.addArguments("--disable-infobars"); //禁用浏览器正在被自动化程序控制的提示 ,但是高版本不生效
if (!pd) {
//无浏览器模式-最大化窗口 ,防止有些元素被隐藏
int screenWidth = ((int) java.awt.Toolkit.getDefaultToolkit().getScreenSize().width);
int screenHeight = ((int) java.awt.Toolkit.getDefaultToolkit().getScreenSize().height);
options.addArguments("window-size=" + screenWidth + "," + screenHeight);
}
//随机设置请求头
options.addArguments("--user-agent=" + UserAgent.getUserAgentWindows());
proxy(options, false); //设置代理 ,true 开启代理
driver = new ChromeDriver(options);//实例化
if (pd) {
driver.manage().window().maximize(); //界面的方式, 最大化窗口, 防止有些元素被隐藏,无界面就不要使用了
}
//当我们去定位页面元素时,如果元素没有找到,不会立即抛出异常,而是周期性地(通常为 0.5s)去重新寻找,直到该元素找到或者超过最大等待时间才结束 ,超时后就报错NoTouchElementException
//当我们使用implicitly_wait()时,如果想要定位的元素已经找到,但是它的内容(如文本内容,属性等)没有加载出来,此时隐式等待无效,仍会直接抛出NoSuchElementException异常,这也是为什么我们很多时候仍需要使用time.sleep()的原因。
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
//无头模式,不加载图片
public static ChromeDriverUtil buildHide(String path) {
return new ChromeDriverUtil(path, false, true);
}
//无头模式,加载图片
public static ChromeDriverUtil buildHideImg(String path) {
return new ChromeDriverUtil(path, false, false);
}
//显示游览器 ,全功能
public static ChromeDriverUtil build(String path) {
return new ChromeDriverUtil(path, true, false);
}
public ChromeDriver getDriver() {
return driver;
}
//强制等待 代码在执行到某个位置时强制等待一段时间
@SneakyThrows
public void sleep(long ms) {
Thread.sleep(ms);
}
// 显示等待,是为了解决隐式等待遗留的问题,比如元素显示了,但是内部的文本没有显示出来,可能文本是通过ajax异步的会比较慢
public WebElement wait(int seconds, ExpectedCondition<WebElement> expectedCondition) {
WebDriverWait webDriverWait = new WebDriverWait(driver, seconds);
//返回null或者false,等待500毫秒继续尝试,直到过期
WebElement until = webDriverWait.until(expectedCondition);
return until;
}
//自行扩展, 从接口中读取,或者从文件中读取都行
private void proxy(ChromeOptions options, boolean pd) {
if (pd) {
String prox = "101.200.127.149:" + 3129;
Proxy p = new Proxy();
p.setHttpProxy(prox);//http
// p.setFtpProxy(prox); //ftp
// p.setSslProxy(prox);//ssl
// p.setSocksProxy(prox); //SOCKS
// p.setSocksUsername("");
// p.setSocksPassword("");
options.setProxy(p);
}
}
}
UserAgent.java
package com.selenium.auto.seleniumjava.util;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import com.google.common.io.Resources;
import java.io.File;
import java.net.URL;
import java.util.Collections;
import java.util.List;
public class UserAgent {
private static List<String> userAgentsWindows = null;
static {
URL url = Resources.getResource("userAgents_windows");
if(url != null) {
File file = new File(url.getPath());
try {
userAgentsWindows = Files.readLines(file, Charsets.UTF_8);
} catch(Exception ex) {}
}
}
public static String getUserAgentWindows() {
if(userAgentsWindows == null || userAgentsWindows.size() == 0) {
return "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36";
}
Collections.shuffle(userAgentsWindows);
return userAgentsWindows.get(0);
}
}
在resources下新建文件userAgents_windows,内容如下:
Mozilla/5.0 (Windows; U; Windows NT 10.0) AppleWebKit/535.11.3 (KHTML, like Gecko) Version/4.0 Safari/535.11.3
Mozilla/5.0 (compatible; MSIE 5.0; Windows NT 6.0; Trident/3.1)
Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 6.1; Trident/4.0)
Mozilla/5.0 (Windows; U; Windows 98) AppleWebKit/534.49.4 (KHTML, like Gecko) Version/4.0.3 Safari/534.49.4
Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 10.0; Trident/3.1)
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/3.1)
Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/24.0.860.0 Safari/535.2
Mozilla/5.0 (Windows CE; mt-MT; rv:1.9.2.20) Gecko/2013-04-30 01:12:55 Firefox/3.8
Mozilla/5.0 (Windows; U; Windows CE) AppleWebKit/533.14.1 (KHTML, like Gecko) Version/5.0.1 Safari/533.14.1
Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.01; Trident/5.0)
Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 6.2; Trident/4.1)
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 10.0; Trident/5.1)
Mozilla/5.0 (Windows NT 5.2; kok-IN; rv:1.9.2.20) Gecko/2011-09-17 16:05:22 Firefox/3.8
Opera/9.36.(Windows NT 6.1; gd-GB) Presto/2.9.178 Version/11.00
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/3.0)
Mozilla/5.0 (Windows NT 6.1; tl-PH; rv:1.9.1.20) Gecko/2017-02-01 17:55:13 Firefox/3.6.14
Mozilla/5.0 (compatible; MSIE 6.0; Windows 98; Trident/5.0)
Mozilla/5.0 (compatible; MSIE 7.0; Windows CE; Trident/3.1)
Mozilla/5.0 (Windows; U; Windows NT 6.1) AppleWebKit/535.41.7 (KHTML, like Gecko) Version/5.0.1 Safari/535.41.7
Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 6.2; Trident/3.0)
Mozilla/5.0 (Windows NT 6.2) AppleWebKit/533.0 (KHTML, like Gecko) Chrome/57.0.812.0 Safari/533.0
Opera/9.85.(Windows NT 5.2; kk-KZ) Presto/2.9.172 Version/12.00
Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.2; Trident/3.1)
Mozilla/5.0 (Windows; U; Windows 95) AppleWebKit/535.8.1 (KHTML, like Gecko) Version/4.0.1 Safari/535.8.1
Opera/9.39.(Windows 98; Win 9x 4.90; cmn-TW) Presto/2.9.189 Version/10.00
Mozilla/5.0 (Windows NT 4.0) AppleWebKit/531.2 (KHTML, like Gecko) Chrome/14.0.876.0 Safari/531.2
Mozilla/5.0 (Windows; U; Windows NT 4.0) AppleWebKit/531.4.5 (KHTML, like Gecko) Version/5.0.3 Safari/531.4.5
Opera/9.18.(Windows 98; Win 9x 4.90; aa-ER) Presto/2.9.166 Version/12.00
Mozilla/5.0 (Windows 95; ml-IN; rv:1.9.2.20) Gecko/2018-05-02 05:15:13 Firefox/3.8
Opera/9.52.(Windows NT 5.1; mhr-RU) Presto/2.9.160 Version/10.00
Mozilla/5.0 (compatible; MSIE 8.0; Windows CE; Trident/5.0)
Mozilla/5.0 (Windows NT 5.1; nan-TW; rv:1.9.1.20) Gecko/2020-02-12 23:57:29 Firefox/6.0
Mozilla/5.0 (Windows NT 4.0; cv-RU; rv:1.9.1.20) Gecko/2016-08-13 23:30:24 Firefox/3.8
Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 4.0; Trident/5.1)
Opera/9.34.(Windows NT 6.1; szl-PL) Presto/2.9.182 Version/12.00
Mozilla/5.0 (compatible; MSIE 7.0; Windows 98; Win 9x 4.90; Trident/4.0)
Opera/8.35.(Windows NT 5.0; az-AZ) Presto/2.9.171 Version/12.00
Opera/9.85.(Windows 98; sr-RS) Presto/2.9.167 Version/10.00
Mozilla/5.0 (Windows NT 5.1; ru-UA; rv:1.9.0.20) Gecko/2011-12-14 02:08:36 Firefox/3.8
Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/3.0)
Mozilla/5.0 (Windows NT 4.0) AppleWebKit/536.2 (KHTML, like Gecko) Chrome/28.0.862.0 Safari/536.2
Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 6.0; Trident/5.1)
Opera/9.50.(Windows NT 5.0; mk-MK) Presto/2.9.161 Version/11.00
Mozilla/5.0 (compatible; MSIE 5.0; Windows NT 6.0; Trident/5.1)
Opera/8.41.(Windows NT 5.01; az-IN) Presto/2.9.177 Version/11.00
Mozilla/5.0 (compatible; MSIE 8.0; Windows 98; Trident/3.0)
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 4.0; Trident/4.1)
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.2; Trident/4.0)
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/4.1)
Mozilla/5.0 (Windows; U; Windows 98) AppleWebKit/531.36.3 (KHTML, like Gecko) Version/4.0.3 Safari/531.36.3
Mozilla/5.0 (compatible; MSIE 6.0; Windows 98; Win 9x 4.90; Trident/4.0)
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)
Mozilla/5.0 (compatible; MSIE 8.0; Windows 98; Trident/4.1)
Mozilla/5.0 (Windows NT 4.0) AppleWebKit/536.2 (KHTML, like Gecko) Chrome/39.0.826.0 Safari/536.2
Mozilla/5.0 (Windows; U; Windows CE) AppleWebKit/533.1.3 (KHTML, like Gecko) Version/4.0.2 Safari/533.1.3
Mozilla/5.0 (compatible; MSIE 5.0; Windows NT 5.1; Trident/5.1)
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/5.1)
Mozilla/5.0 (Windows; U; Windows 95) AppleWebKit/531.4.2 (KHTML, like Gecko) Version/5.1 Safari/531.4.2
Mozilla/5.0 (Windows NT 5.01; tr-CY; rv:1.9.2.20) Gecko/2013-09-06 07:39:53 Firefox/9.0
Mozilla/5.0 (Windows; U; Windows NT 4.0) AppleWebKit/535.22.1 (KHTML, like Gecko) Version/5.0 Safari/535.22.1
Mozilla/5.0 (Windows; U; Windows NT 5.0) AppleWebKit/535.37.3 (KHTML, like Gecko) Version/4.1 Safari/535.37.3
Opera/8.64.(Windows NT 5.1; yue-HK) Presto/2.9.182 Version/10.00
Opera/8.27.(Windows NT 6.1; bo-CN) Presto/2.9.180 Version/12.00
Opera/9.82.(Windows NT 5.01; lij-IT) Presto/2.9.185 Version/12.00
Opera/8.12.(Windows CE; ne-NP) Presto/2.9.160 Version/12.00
Opera/8.55.(Windows NT 5.1; it-CH) Presto/2.9.171 Version/10.00
Mozilla/5.0 (Windows; U; Windows NT 5.0) AppleWebKit/532.45.4 (KHTML, like Gecko) Version/4.0.2 Safari/532.45.4
Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/4.0)
Mozilla/5.0 (Windows; U; Windows 98; Win 9x 4.90) AppleWebKit/532.32.3 (KHTML, like Gecko) Version/4.0 Safari/532.32.3
Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 5.0; Trident/5.1)
Opera/9.26.(Windows CE; af-ZA) Presto/2.9.172 Version/10.00
Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 6.1; Trident/5.1)
Mozilla/5.0 (compatible; MSIE 7.0; Windows 98; Win 9x 4.90; Trident/5.0)
Mozilla/5.0 (Windows NT 5.1; or-IN; rv:1.9.0.20) Gecko/2012-05-22 18:16:14 Firefox/3.8
Mozilla/5.0 (Windows; U; Windows NT 6.2) AppleWebKit/533.29.5 (KHTML, like Gecko) Version/5.0.5 Safari/533.29.5
Opera/9.93.(Windows 98; ka-GE) Presto/2.9.184 Version/12.00
Mozilla/5.0 (Windows NT 5.1) AppleWebKit/531.2 (KHTML, like Gecko) Chrome/29.0.812.0 Safari/531.2
Mozilla/5.0 (Windows; U; Windows CE) AppleWebKit/533.43.7 (KHTML, like Gecko) Version/5.1 Safari/533.43.7
Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 5.2; Trident/5.1)
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.2; Trident/3.0)
Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/3.1)
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.01; Trident/5.0)
Opera/9.75.(Windows NT 5.01; as-IN) Presto/2.9.180 Version/11.00
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 5.0; Trident/3.1)
Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)
Mozilla/5.0 (Windows NT 5.0) AppleWebKit/536.2 (KHTML, like Gecko) Chrome/24.0.826.0 Safari/536.2
Mozilla/5.0 (Windows 95; nb-NO; rv:1.9.1.20) Gecko/2013-09-05 15:16:44 Firefox/11.0
Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.2 (KHTML, like Gecko) Chrome/52.0.861.0 Safari/536.2
Mozilla/5.0 (compatible; MSIE 6.0; Windows NT 10.0; Trident/3.0)
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.0; Trident/4.0)
Mozilla/5.0 (compatible; MSIE 5.0; Windows 98; Win 9x 4.90; Trident/3.0)
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/3.0)
Mozilla/5.0 (Windows; U; Windows NT 6.2) AppleWebKit/533.35.5 (KHTML, like Gecko) Version/5.0 Safari/533.35.5
Mozilla/5.0 (compatible; MSIE 7.0; Windows NT 6.1; Trident/5.1)
Mozilla/5.0 (Windows 98; Win 9x 4.90) AppleWebKit/532.2 (KHTML, like Gecko) Chrome/60.0.830.0 Safari/532.2
Opera/8.23.(Windows NT 5.2; byn-ER) Presto/2.9.189 Version/11.00
Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.0; Trident/5.1)
Opera/9.93.(Windows NT 5.1; az-AZ) Presto/2.9.173 Version/10.00
Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/52.0.845.0 Safari/535.1
Mozilla/5.0 (compatible; MSIE 8.0; Windows 95; Trident/3.1)
使用:
//驱动位置
String path = "D:\\selenium\\chromedriver_win32\\chromedriver.exe";
ChromeDriverUtil util = ChromeDriverUtil.build(path);
ChromeDriver driver = util.getDriver();
driver.navigate().to("https://www.baidu.com");
验证浏览器驱动
WebDriver driver = new ChromeDriver(); //Chrome浏览器
WebDriver driver = new FirefoxDriver(); //Firefox浏览器
WebDriver driver = new EdgeDriver(); //Edge浏览器
WebDriver driver = new InternetExplorerDriver(); // Internet Explorer浏览器
WebDriver driver = new OperaDriver(); //Opera浏览器
WebDriver driver = new PhantomJSDriver(); //PhantomJS
Selenium八种定位方式
- findElement(By.id())
- findElement(By.name())
- findElement(By.className())
- findElement(By.tagName())
- findElement(By.linkText())
- findElement(By.partialLinkText())
- findElement(By.xpath())
- findElement(By.cssSelector())
控制浏览器
driver.navigate.refresh(); //刷新
driver.navigate.forward(); //后退
driver.navigate.back(); //前进
driver.manage().window().maximize(); //浏览器最大化
driver.manage().window().setSize(new Dimension(480,800));
1.WebDriver 常用方法
- clear() 清除文本。
- sendKeys(*value) 模拟按键输入。
- click() 单击元素
sendKeys()方法模拟键盘向输入框里输入内容。 但是它的作用不仅于此, 我们还可以用它发送键盘按键, 甚至用它来指定上传的文件。
click()方法可以用来单击一个元素,前提是它是可以被单击的对象,它与 sendKeys()方法是Web页面操作中最常用到的两个方法。 其实click()方法不仅仅用于单击一个按钮,它还可以单击任何可以单击的文字/图片链接、复选框、单选框、下拉框等。
2.其它常用方法
- submit() //提交表单
- getSize() 返回元素的尺寸。
- getText() 获取元素的文本。
- getAttribute(name) 获得属性值。
- isDisplayed() 设置该元素是否用户可见。
(八)模拟鼠标操作
- contextClick() 右击
- clickAndHold() 鼠标点击并控制
- doubleClick() 双击
- dragAndDrop() 拖动
- release() 释放鼠标
- perform() 执行所有Actions中存储的行为
(九)模拟键盘操作
Keys()类提供了键盘上几乎所有按键的方法。 前面了解到, sendKeys()方法可以用来模拟键盘输入, 除此之 外, 我们还可以用它来输入键盘上的按键, 甚至是组合键, 如 Ctrl+A、 Ctrl+C 等。
WebElement input = driver.findElement(By.id("kw"));
input.sendkeys(Keys.CONTROL,"a"); //复制
input.sendkeys(Keys.CONTROL,"x"); //剪切
input.sendkeys(Keys.CONTROL,"v"); //粘贴
(十)获取断言信息
不管是在做功能测试还是自动化测试,最后一步需要拿实际结果与预期进行比较。这个比较的称之为断言。
我们通常可以通过获取title 、URL和text等信息进行断言。text方法在前面已经讲过,它用于获取标签对之间的文本信息。
- getTitle(): 用于获得当前页面的title。
- getCurrentUrl() : 用户获得当前页面的URL。
- getText() 获取页面文本信息。
(十二)定位一组元素
与定位单个元素类似,findElement后面多加了个s
(十八)浏览器cookie操作
- getCookies() 获得所有 cookie 信息。
- getCookieNamed(String name) 返回字典的key为“name”的Cookie信息。
- addCookie(cookie dict) 添加Cookie。“cookie_dict”指字典对象,必须有 name和value值。
- deleteCookieNamed(String name) 删除Cookie 信息。 “name”是要删除的 cookie的名称; “optionsString” 是该Cookie的选项,目前支持的选项包括“路径” , “域” 。
- deleteAllCookies() 删除所有 cookie 信息。