1、pom
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
</dependency>
2、腳本動态獲取網頁高度
// 設置驅動地(land)址
System.setProperty("webdriver.chrome.driver", "D:\\apps\\headless\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
// 設置谷歌浏覽器exe文件所在(exist)地(land)址
options.setBinary("C:\\Users\\qizhan\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");
// 這(this)裏是(yes)要(want)執行的(of)命令,如需修改截圖頁面的(of)尺寸,修改--window-size的(of)參數即可
options.addArguments("--headless", "--disable-gpu", "--window-size=1920,1200", "--ignore-certificate-errors");
ChromeDriver driver = new ChromeDriver(options);
// 訪問頁面
driver.get("http://sina.com.cn");
//執行腳本
String js1 = "return document.body.clientHeight.toString()";
String js1_result = driver.executeScript(js1) + "";
int height = Integer.parseInt(js1_result);
driver.manage().window().setSize(new Dimension(830, height + 100));
// 頁面等待渲染時(hour)長,如果你的(of)頁面需要(want)動态渲染數據的(of)話一(one)定要(want)留出(out)頁面渲染的(of)時(hour)間,單位默認是(yes)秒
Wait<WebDriver> wait = new WebDriverWait(driver, 3);
wait.until(new ExpectedCondition<WebElement>() {
public WebElement apply(WebDriver d) {
// 等待前台頁面中 id爲(for)“kw”的(of)組件渲染完畢,後截圖
// 若無需等待渲染,return true即可。 不(No)同頁面視情況設置id
return d.findElement(By.id("app"));
}
});
// 獲取到(arrive)截圖的(of)文件
File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
if ((screenshotFile != null) && screenshotFile.exists()) {
// 截取到(arrive)的(of)圖片存到(arrive)本地(land)
FileOutputStream out = null;
FileInputStream in = null;
try {
in = new FileInputStream(screenshotFile);
out = new FileOutputStream("D:\\apps\\headless\\cut1.png");
byte[] b = new byte[1024];
while (true) {
int temp = in.read(b, 0, b.length);
// 如果temp = -1的(of)時(hour)候,說明讀取完畢
if (temp == -1) {
break;
}
out.write(b, 0, temp);
}
} catch (Exception e) {
// TODO異常處理
}
}