官网: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. 正着打星星(js)

    //让用户输入行数,使用for循环嵌套打出正着的星星来,行数等于用户输入的数字 //例如:用户输入6 // * // *** // ***** // ******* // ********* // * ...

  2. ASP.NET实现验证码图片

    新建一个checkcode.aspx文件,页面中不用写任何东西,在代码中,Page_Load中写入如下代码: string chkCode = string.Empty;        int ix, ...

  3. [工具] fierce--子域收集

    简介 fierce 是使用多种技术来扫描目标主机IP地址和主机名的一个DNS服务器枚举工具.运用递归的方式来工作.它的工作原理是先通过查询本地DNS服务器来查找目标DNS服务器,然后使用目标DNS服务 ...

  4. 清除input输入框的历史记录

    当之前的input框输入了数据后,下次输入有历史记录问题的解决方法 <input id="vhcl_no"  type="text"  autocompl ...

  5. select ... into outfile备份及恢复使用

    select ... into outfile语句是一种逻辑备份的方法,更准确地说是导出一张表中的数据. Syntax:SELECT    [ALL | DISTINCT | DISTINCTROW ...

  6. MariaDB基本命令

    --查看当前日期select current_date();--查看当前时间select current_time();--查看当前日期.时间select now();--查看当前用户select u ...

  7. fastclick无需对IOS11及以上做处理

    // 解决click点击300毫秒延时问题 (IOS11及以上无需处理) import FastClick from 'fastclick' const device = navigator.user ...

  8. vue 图片滑动登录

    前言 最近在研究图片滑动解锁 登录,说是要用阿里的那个验证,但是还是想自己手写下这个Demo 效果图是这样的: 本来是想用canvas 来实现的,但是类,后来还想用css 和图片来代替canvas 其 ...

  9. TXNLP 33-40

    词向量: 回顾基于检索的问答系统 倒排表解决:坑爹的翻译...应该翻译成“反向索引” 常规的索引是文档到关键词的映射: 文档——>关键词但是这样检索关键词的时候很费力,要一个文档一个文档的遍历一 ...

  10. c语言结构体以及结构体指针的使用

    结构体: 正常定义一个结构体: typedef struct node{ ]; int len; }Seq,*llink; 定义结构体指针: Seq *s;或者llink t;之后关于s与t的用法,其 ...