准备工作:
1.安装Chrome浏览器
2.安装与Chrome适配的版本ChromeDriver
Chrome下载地址:https://blog.csdn.net/yuan2019035055/article/details/136607093
ChromeDriver下载地址:CNPM Binaries Mirror
selenium官网地址:Selenium
Maven仓库:
<!--3.x支持java8;4.x需要java11及以上--> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>3.141.59</version> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>27.0-jre</version> </dependency>
代码:
package com.laoyao.project;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.File;
import java.util.concurrent.TimeUnit;
public class ElementSnapshot {
public static void main(String[] args) throws Exception {
//chromedriver是与 Google Chrome 浏览器进行自动化测试的工具
System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");
//设置ChromeOptions打开方式,设置headless:不弹出浏览器
ChromeOptions options = new ChromeOptions();
options.addArguments("headless");
//设置好使用ChromeDriver使用
ChromeDriver driver = new ChromeDriver(options);
//设置超时时间
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
//获取要截图的地址,注:需要先获取地址,不然下方获取的宽度高度就会是弹窗的高和宽,而不是页面内容的高宽
driver.get("https://blog.csdn.net/qq_52066082?type=blog");
//获取页面高宽使用:return document.documentElement.scrollWidth
Long width = (Long) ((JavascriptExecutor) driver).executeScript("return document.documentElement.scrollWidth");
Long height = (Long) ((JavascriptExecutor) driver).executeScript("return document.documentElement.scrollHeight");
//设置浏览器弹窗页面的大小
driver.manage().window().setSize(new Dimension(width.intValue(), height.intValue()));
//使用getScreenshotAs进行截取屏幕
File srcFile = driver.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile, new File("D:\\IT老姚.png"));
}
}