官网: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)的更多相关文章

  1. 自动化测试Java一:Selenium入门

    From: https://blog.csdn.net/u013258415/article/details/77750214 Selenium入门 欢迎阅读Selenium入门讲义,本讲义将会重点介 ...

  2. webdriver入门-Java

    webdriver入门-Java   如何用webdriver打开一个浏览器,我们常用的浏览器有firefox和IE两种,firefox是selenium支持得比较成熟的浏览器,很多新的特性都会在fi ...

  3. Selenium自动化测试Python一:Selenium入门

    Selenium入门 欢迎阅读Selenium入门讲义,本讲义将会重点介绍Selenium的入门知识以及Selenium的前置知识. 自动化测试的基础 在Selenium的课程以前,我们先回顾一下软件 ...

  4. Selenium Webdriver java 积累一

    Selenium Webdriver 学习: http://jarvi.iteye.com/category/203994 https://github.com/easonhan007/webdriv ...

  5. [selenium webdriver Java]常用api

    1. 获取元素文本 WebElement类的getText()方法返回元素的innerText属性.所以元素里如果有子节点一样也会被返回出来.如下所示 public class GetText { @ ...

  6. 9天快速入门java

    Java入门教程[9天快速入门JAVA] §1.3.简单的Java程序 下面我们先介绍两个简单的Java程序,并对其进行分析. 例1.1. public class HelloWorldApp{//a ...

  7. selenium 3+java 配置全

    之前有配置过java+selenium的环境,感觉将的不够详细,这里重新写一篇,以便日后复习,和大家共享. 一.准备工作. 首先在配置之前需要准备以下:   JDK    Eclipse    Sel ...

  8. Selenium 入门到精通系列:六

    Selenium 入门到精通系列 PS:Checkbox方法 例子 HTML: <html> <head> <title>测试页面</title> &l ...

  9. Selenium 入门到精通系列:五

    Selenium 入门到精通系列 PS:显式等待.隐式等待.强制等待方法 例子 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019 ...

  10. Selenium 入门到精通系列:四

    Selenium 入门到精通系列 PS:鼠标右键.鼠标悬停.键盘操作方法 例子 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2019 ...

随机推荐

  1. 微信小程序点击复制功能

    wx.setClipboardData({ data: '这是要复制的文字', success: function (res) { wx.showModal({ title: '提示', conten ...

  2. Java高并发程序设计学习笔记(五):JDK并发包(各种同步控制工具的使用、并发容器及典型源码分析(Hashmap等))

    转自:https://blog.csdn.net/dataiyangu/article/details/86491786#2__696 1. 各种同步控制工具的使用1.1. ReentrantLock ...

  3. CDH6.1.0新增主机资源

    在CDH 6.1.0 上增加主机 一 客户端配置 1.1 JAVA 配置 1.2 关闭selinux以及防火墙 1.3 将服务端的agent包打包然后拷贝到客户端 然后解压 启动(也可以rpm安装) ...

  4. Photoshop从入门到精通所有视频教程(43G)以及素材资料免费拿

    包含了Photoshop从入门到精通所有需要了解的视频教程资料,并且包含了大量的P图素材. 资料获取方式,关注公总号RaoRao1994,查看往期精彩-所有文章,即可获取资源下载链接 更多资源获取,请 ...

  5. php--常见算法2

    <?php function zhi($number){ $f1=1; $f2=1; for($i=3;$i<=$number;$i++){ //前一个的前一个值+前一个值 $f3=$f1 ...

  6. BLE 5协议栈-属性协议层(ATT)

    文章转载自:http://www.sunyouqun.com/2017/04/page/2/ 属性协议(Attribute Protocol)简称ATT. ATT层定义了属性实体的概念,包括UUID. ...

  7. js实现购物车数量的增加与减少,js实现购物车数量的自增与自减

    js实现购物车数量的增加与减少,js实现购物车数量的自增与自减 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//E ...

  8. datax部署

    1.下载: https://github.com/alibaba/DataX Clone or download下载源码,拉到下面 Quick Start Download DataX下载地址 下载安 ...

  9. usb发送字节

  10. git fetch和pull的区别

    Git中从远程的分支获取最新的版本到本地有这样2个命令: 1. git fetch:相当于是从远程获取最新版本到本地,不会自动merge   1 2 3 Git fetch origin master ...