selenium 入门(Java)
官网:https://www.seleniumhq.org/
下载地址:https://sites.google.com/a/chromium.org/chromedriver/downloads
华为镜像地址:https://mirrors.huaweicloud.com/chromedriver/
阿里镜像地址:https://npm.taobao.org/mirrors/chromedriver/
下载时,浏览器版本与 selenium 驱动版本要对应。
引入依赖,这里测试了 chrome 与 ie
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>3.141.59</version>
<exclusions>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
</exclusions>
</dependency> <dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-ie-driver</artifactId>
<version>3.141.59</version>
<exclusions>
<exclusion>
<artifactId>guava</artifactId>
<groupId>com.google.guava</groupId>
</exclusion>
</exclusions>
</dependency> <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.0-jre</version>
</dependency>
一、HelloWorld
打开浏览器,打开网页,关闭浏览器。
static {
// IE浏览器 (webdriver.ie.driver)
// 火狐浏览器 (webdriver.gecko.driver)
// 谷歌浏览器 (webdriver.chrome.driver)
System.setProperty("webdriver.chrome.driver", "D:\\selenium\\chromedriver.exe");
System.setProperty("webdriver.chrome.bin", "D:\\selenium\\chrome.exe");
System.setProperty("webdriver.ie.driver", "D:\\selenium\\IEDriverServer.exe");
System.setProperty("webdriver.ie.bin", "C:\\Program Files\\internet explorer\\iexplore.exe");
}
/**
* https://www.seleniumhq.org/download/
* https://sites.google.com/a/chromium.org/chromedriver/downloads
*/
public static void main(String[] args) {
// chrome();
ie();
}
public static void chrome() {
WebDriver driver = null;
try {
// InternetExplorerDriver() 浏览器
// FirefoxDriver() 火狐浏览器
// ChromeDriver() 谷歌浏览器
driver = new ChromeDriver();
driver.get("https://www.baidu.com/");
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (driver != null) {
// 关闭浏览器当前窗口
driver.close();
// 退出 webdriver 并关闭浏览器
driver.quit();
}
}
}
/**
* Internet 选项->安全:四个区域的保护模式全部去掉勾选
* regedit
* \HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Zones\(0-4) 2500(0->3)
*/
public static void ie() {
WebDriver driver = null;
try {
driver = new InternetExplorerDriver();
driver.get("https://www.baidu.com/");
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (driver != null) {
driver.close();
driver.quit();
}
}
}
二、查找元素节点并获取元素信息
selenium 使用的时 xpath 语法
注意 iframe 标签,需要先切换(driver.switchTo().frame(element))才能获取其中的元素。
static {
System.setProperty("webdriver.chrome.driver", "D:\\selenium\\chromedriver.exe");
System.setProperty("webdriver.chrome.bin", "D:\\selenium\\chrome.exe");
}
public static void main(String[] args) {
WebDriver driver = null;
try {
driver = new ChromeDriver();
driver.get("https://www.baidu.com/");
// 在定位元素时,对所有元素设置超时时间,超出了设置时间则抛出异常
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
// xpath
WebElement element = driver.findElement(By.xpath("//a[@id='jgwab']"));
System.out.println(element.getText());
System.out.println(element.getAttribute("target"));
// 选择器
element = driver.findElement(By.className("qrcode-text")).findElement(By.className("sub-title"));
System.out.println(element.getText());
System.out.println(element.getTagName());
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (driver != null) {
driver.close();
driver.quit();
}
}
}
三、动作链
找到元素节点后,对节点进行点击、输入、滑动等操作。
static {
System.setProperty("webdriver.chrome.driver", "D:\\selenium\\chromedriver.exe");
System.setProperty("webdriver.chrome.bin", "D:\\selenium\\chrome.exe");
}
/**
* 1. 鼠标左键点击
* Actions action = new Actions(driver);
* action.click(); //鼠标左键点击当前停留的位置
* action.click(driver.findElement(By.id(“kw”))); //鼠标左键点击指定的元素对象
* <p>
* 2. 鼠标右键点击
* Actions action = new Actions(driver);
* action.contextClick(); //鼠标右键点击当前停留的位置
* action.contextClick(driver.findElement(By.id(“kw”))); //鼠标右键点击指定的元素对象
* <p>
* 3. 鼠标双击
* Actions action = new Actions(driver);
* action.doubleClick(); //鼠标双击当前停留的位置
* action.doubleClick(driver.findElement(By.id(“kw”))); //鼠标双击指定的元素对象
* <p>
* 4. 鼠标拖拽
* Actions action = new Actions(driver);
* action.dragAndDrop(el1,el2); //鼠标将el1元素拖放到el2元素的位置
* action.dragAndDrop(el1,x,y); //鼠标el1元素拖放到(x, y)位置,x为横坐标,y为纵坐标
* <p>
* 5. 鼠标悬停
* Actions action = new Actions(driver);
* action.clickAndHold(el); //鼠标悬停在el元素的位置
* <p>
* 6. 鼠标移动
* Actions action = new Actions(driver);
* action.moveToElement(el); //将鼠标移到el元素
* action.moveToElement(el,x,y); //将鼠标移到元素el的 (x, y) 位置
* <p>
* 7. 鼠标释放
* action.release(); //释放鼠标
*/
public static void main(String[] args) {
WebDriver driver = null;
try {
driver = new ChromeDriver();
WebElement element = null;
Actions actions = new Actions(driver);
// 输入,点击
// driver.get("https://www.baidu.com/");
// element = driver.findElement(By.id("kw"));
// actions.sendKeys(element, "yofc").click(driver.findElement(By.xpath("//*[@id=\"su\"]"))).perform();
// form
// driver.get("http://127.0.5.1:81/user-login.html");
// element = driver.findElement(By.xpath("//input[@name='account']"));
// element.sendKeys("yonghuming");
// element = driver.findElement(By.xpath("//input[@name='password']"));
// element.sendKeys("mima");
// element = driver.findElement(By.className("form-condensed"));
// element.submit();
// update file
// driver.get("https://imgurl.org/");
// element = driver.findElement(By.className("layui-upload-file"));
// element.sendKeys("D:\\selenium\\test.jpg");
// 滑动
// driver.get("http://www.jq22.com/yanshi20053");
//
// element = driver.findElement(By.id("iframe"));
// driver.switchTo().frame(element);
//
// element = driver.findElement(By.className("slider"));
// actions.dragAndDropBy(element, 100, 0).perform();
// 执行 js
driver.get("https://www.baidu.com/");
JavascriptExecutor je = (JavascriptExecutor) driver;
je.executeScript("alert('hello!')");
// 缩放
// je.executeScript("document.getElementsByTagName('body')[0].style.zoom=0.5");
// 新窗口打开网页
// je.executeScript("window.open('http://www.baidu.com')");
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (driver != null) {
driver.close();
driver.quit();
}
}
}
四、启动参数(chrome)
在浏览器启动时,加一些参数以实现一些功能。
static {
System.setProperty("webdriver.chrome.driver", "D:\\selenium\\chromedriver.exe");
System.setProperty("webdriver.chrome.bin", "D:\\selenium\\chrome.exe");
}
public static void main(String[] args) {
WebDriver driver = null;
try {
ChromeOptions co = new ChromeOptions();
co.addArguments("user-data-dir=D:\\selenium\\User Data");
// 无窗口模式
co.addArguments("headless");
// co.addArguments("lang=zh_CN.UTF-8");
// 代理
// co.addArguments("proxy-server=http://183.143.41.69:8888");
co.addArguments("user-agent='MQQBrowser/26 Mozilla/5.0 (Linux; U; Android 2.3.7; zh-cn; MB200 Build/GRJ22; CyanogenMod-7) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1'");
driver = new ChromeDriver(co);
// 浏览器窗口大小
driver.manage().window().setSize(new Dimension(500,500));
// driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.get("https://www.baidu.com/");
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (driver != null) {
driver.close();
driver.quit();
}
}
}
五、JS 注入
让没有引入某些 js 的网页引入指定 js。
static {
System.setProperty("webdriver.chrome.driver", "D:\\selenium\\chromedriver.exe");
System.setProperty("webdriver.chrome.bin", "D:\\selenium\\chrome.exe");
}
public static void main(String[] args) {
WebDriver driver = null;
try {
driver = new ChromeDriver();
driver.get("http://127.0.0.1:8080");
JavascriptExecutor je = ((JavascriptExecutor) driver);
try {
je.executeScript("alert(jQuery()==null)");
Thread.sleep(3000);
} catch (WebDriverException e) {
je.executeScript("var h = document.getElementsByTagName('head')[0];"
+ "var ns = document.createElement('script');"
+ "ns.type = 'text/javascript';"
+ "ns.src = 'http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js';"
+ "h.appendChild(ns);");
}
Thread.sleep(1000);
je.executeScript("alert(jQuery()==null)");
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (driver != null) {
driver.close();
driver.quit();
}
}
}
六、截图
可以截取网页指定区域
static {
System.setProperty("webdriver.chrome.driver", "D:\\selenium\\chromedriver.exe");
System.setProperty("webdriver.chrome.bin", "D:\\selenium\\chrome.exe");
}
public static void main(String[] args) {
WebDriver driver = null;
try {
driver = new ChromeDriver();
driver.get("https://www.baidu.com/");
WebElement element = driver.findElement(By.className("index-logo-src"));
File file = captureElement(driver, element);
copyFile(file,new File("D:\\123.png"));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (driver != null) {
driver.close();
driver.quit();
}
}
}
private static File captureElement(WebDriver driver, WebElement element) throws Exception {
// 整个网页
File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage img = ImageIO.read(screen);
// 获得元素的高度和宽度
int width = element.getSize().getWidth();
int height = element.getSize().getHeight();
// 创建一个矩形使用上面的高度,和宽度
Rectangle rect = new Rectangle(width, height);
// 得到元素的坐标
Point p = element.getLocation();
// 从整个网页中截取指定元素
BufferedImage dest = img.getSubimage(p.getX(), p.getY(), rect.width, rect.height);
// 存为png格式
ImageIO.write(dest, "png", screen);
return screen;
}
private static void copyFile(File source, File dest) throws IOException {
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(source);
output = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) != -1) {
output.write(buf, 0, bytesRead);
}
} finally {
input.close();
output.close();
}
}
https://www.cnblogs.com/wuyn/p/10057236.html
selenium 入门(Java)的更多相关文章
- 自动化测试Java一:Selenium入门
From: https://blog.csdn.net/u013258415/article/details/77750214 Selenium入门 欢迎阅读Selenium入门讲义,本讲义将会重点介 ...
- webdriver入门-Java
webdriver入门-Java 如何用webdriver打开一个浏览器,我们常用的浏览器有firefox和IE两种,firefox是selenium支持得比较成熟的浏览器,很多新的特性都会在fi ...
- Selenium自动化测试Python一:Selenium入门
Selenium入门 欢迎阅读Selenium入门讲义,本讲义将会重点介绍Selenium的入门知识以及Selenium的前置知识. 自动化测试的基础 在Selenium的课程以前,我们先回顾一下软件 ...
- Selenium Webdriver java 积累一
Selenium Webdriver 学习: http://jarvi.iteye.com/category/203994 https://github.com/easonhan007/webdriv ...
- [selenium webdriver Java]常用api
1. 获取元素文本 WebElement类的getText()方法返回元素的innerText属性.所以元素里如果有子节点一样也会被返回出来.如下所示 public class GetText { @ ...
- 9天快速入门java
Java入门教程[9天快速入门JAVA] §1.3.简单的Java程序 下面我们先介绍两个简单的Java程序,并对其进行分析. 例1.1. public class HelloWorldApp{//a ...
- selenium 3+java 配置全
之前有配置过java+selenium的环境,感觉将的不够详细,这里重新写一篇,以便日后复习,和大家共享. 一.准备工作. 首先在配置之前需要准备以下: JDK Eclipse Sel ...
- Selenium 入门到精通系列:六
Selenium 入门到精通系列 PS:Checkbox方法 例子 HTML: <html> <head> <title>测试页面</title> &l ...
- Selenium 入门到精通系列:五
Selenium 入门到精通系列 PS:显式等待.隐式等待.强制等待方法 例子 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019 ...
- Selenium 入门到精通系列:四
Selenium 入门到精通系列 PS:鼠标右键.鼠标悬停.键盘操作方法 例子 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019 ...
随机推荐
- app hellocharts 柱状图
app里有个告警数量的柱状图,有点小问题,y轴竟然不是整数 这个改起来到是简单 Axis yAxis = new Axis().setHasLines(true).setTextColor(Color ...
- 《python解释器源码剖析》第2章--python中的int对象
2.0 序 在所有的python内建对象中,整数对象是最简单的对象.从对python对象机制的剖析来看,整数对象是一个非常好的切入点.那么下面就开始剖析整数对象的实现机制 2.1 初识PyLongOb ...
- 【TCP】拥塞控制
TCP拥塞控制 出现拥塞 ∑对资源的需求 > ∑可用资源 拥塞控制是防止过多的数据注入到网络中,使网络中的路由器或链路不过载,这是一个全局性的. 流量控制是点对点的通信量的控 ...
- 6.Shell 计划任务服务程序
计划任务服务程序 经验丰富的系统运维工程师可以使得Linux在无需人为介入的情况下,在指定的时间段自动启用或停止某些服务或命令,从而实现运维的自动化. 如何设置服务器的计划任务服务,把周期性.规律性的 ...
- Linux 之Ubuntu在VM中安装(桌面版)
1.安装系统 https://jingyan.baidu.com/article/14bd256e0ca52ebb6d26129c.html 2.安装VM Tools https://jingyan. ...
- java8学习之Function与BiFunction函数式接口详解
Function接口: 上次中已经使用了Function的apply()方法,但是在这个接口中还存在三个具体实现的方法,如下: 下面来仔细的将剩下的方法学习一下: compose(): 首先来读一下该 ...
- Summer training #2
A:不管有没有负数 一顿操作之后肯定只有正数 又因为A=A-B 所以最大值是一直在减小的 所以一定有结果 B:..一开始以为求min操作数 WA了2发 直接求所有数的GCD如果所有数的GCD都不是1的 ...
- PHP中把对象转数组的几个方法
PHP中把对象转数组的几个方法: 1. //PHP stdClass Object转array function object_array($array) { if(is_object($array) ...
- PAT乙级1018
题目链接 https://pintia.cn/problem-sets/994805260223102976/problems/994805304020025344 题解 刚开始做很懵逼,可能并不难吧 ...
- System.nanoTime与System.currentTimeMillis
System.nanoTime提供相对精确的计时,但是不能用他来计算当前日期.(系统计时器的当前值,以毫微秒为单位) System.currentTimeMillis返回的是从1970.1.1 UTC ...