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 ...
随机推荐
- BootStrape基础使用
官网:www.bootcss.com 一. 全局css样式 栅格系统 栅格系统用于通过一系列的行(row)与列(column)的组合来创建页面布局 <!DOCTYPE html> < ...
- Nginx作为代理服务之正反代理
Nginx作为代理服务之正反代理 首先什么是代理,就跟明星的经纪人类似,比如作为苍老师经纪人的我,如果你们需要和苍老师拍小电影,可以跟我这个经纪人来商量比如价格啊,时间等相关信息,那么我就作为一个代理 ...
- 08-【jsp重点】
jsp的四个作用域和9个内置对象 jsp内置对象[重点]:pageContext.request.session.application.response.out.page.exception.con ...
- 代码检查工具sonarqube介绍
SonarQube 是一款用于代码质量管理的开源工具,它主要用于管理源代码的质量.通过插件形式,可以支持众多计算机语言. 比如 java, C#, go,C/C++, PL/SQL,Cobol,Jav ...
- 正则表达式 Regular expression为学习助跑
这是一个Regular expression的铁路图(至少我现在是这么称呼的)的图形化界面帮助检验和理解我们所写的Regular expression是否正确. 1.官网 :https://regex ...
- 需求分析&系统设计
这个作业属于哪个课程 课程链接 这个作业要求在哪里 作业要求 团队名称 朋友 代打了解一下 这个作业的目标 需求分析&系统设计 一.团队成员的姓名学号列表 学号 姓名 特长 061126 黄天 ...
- JSON跨域读取那点事(JSONP跨域访问)
最近在码一个小项目,需要远程读取json.因为需求很少,如果引用jquery使用其getjson方法就显得很浪费嘛= = 这篇文章很详细的解释了JSON跨域读取的前世今生,把原理讲得很透彻.特此分享. ...
- SAP 选择屏幕的上方 (sscrfields) 按钮设置
TABLES sscrfields. PARAMETERS: p_carrid TYPE s_carr_id, p_cityfr TYPE s_from_cit. , "激活按钮 . INI ...
- WPF绑定命令
一.目的 降低代码耦合度(降低UI层和BLL层的代码耦合度),将UI层的后台代码更好的转移到BLL层中,让视图和业务逻辑分离的更好 二.使用方式 1.创建一个RelayCommand,继承IComma ...
- IO框架:asyncio 下篇
动态添加协程 在实战之前,我们要先了解下在asyncio中如何将协程态添加到事件循环中的.这是前提. 如何实现呢,有两种方法: 主线程是同步的 import time import asyncio f ...