官网: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
来源:oschina
链接:https://my.oschina.net/u/4419355/blog/3452175