1、pom
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
</dependency>
2、腳本動态獲取網頁(yè)高度
// 設置驅動地址
System.setProperty("webdriver.chrome.driver", "D:\\apps\\headless\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
// 設置谷歌浏覽器exe文(wén)件所在地址
options.setBinary("C:\\Users\\qizhan\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe");
// 這裏是要執行的命令,如需修改截圖頁(yè)面的尺寸,修改--window-size的參數即可(kě)
options.addArguments("--headless", "--disable-gpu", "--window-size=1920,1200", "--ignore-certificate-errors");
ChromeDriver driver = new ChromeDriver(options);
// 訪問頁(yè)面
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));
// 頁(yè)面等待渲染時長(cháng),如果你的頁(yè)面需要動态渲染數據的話一定要留出頁(yè)面渲染的時間,單位默認是秒(miǎo)
Wait<WebDriver> wait = new WebDriverWait(driver, 3);
wait.until(new ExpectedCondition<WebElement>() {
public WebElement apply(WebDriver d) {
// 等待前台頁(yè)面中(zhōng) id為(wèi)“kw”的組件渲染完畢,後截圖
// 若無需等待渲染,return true即可(kě)。 不同頁(yè)面視情況設置id
return d.findElement(By.id("app"));
}
});
// 獲取到截圖的文(wén)件
File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
if ((screenshotFile != null) && screenshotFile.exists()) {
// 截取到的圖片存到本地
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的時候,說明讀取完畢
if (temp == -1) {
break;
}
out.write(b, 0, temp);
}
} catch (Exception e) {
// TODO異常處理(lǐ)
}
}