java使用Selenium+EdgeDriver實現截圖並保存(包含滾動條未顯示部分)


在使用Selenium+EdgeDriver之前做一些准備工作

一、檢查當前Edge瀏覽器版本號

 

 

 

 

 

 

 

二、下載EdgeDriver 驅動

百度搜索“EdgeDriver” 

 

 或者直接:https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

選擇下載對應大版本,小版本最接近當前瀏覽器的驅動

我目前瀏覽器的版本是:95.0.1020.53

我選擇的Edge驅動版本:95.0.1020.44

 

 下載完成后文件名一般叫“edgedriver_win64.zip”

例如復制到“D:\”盤,解壓“D:\edgedriver_win64”

那么驅動部門就准備好了!

Maven:

<dependency>
    <groupId>org.seleniumhq.selenium</groupId>
    <artifactId>selenium-java</artifactId>
    <version>4.0.0</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

TestScreen.java

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.support.ui.FluentWait;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class TestScreen {
    public static void main(String[] args) throws IOException {
        //驅動程序所在位置
        System.setProperty("webdriver.edge.driver", "D:\\edgedriver_win64\\msedgedriver.exe");
        EdgeDriver driver = new EdgeDriver();
        System.out.println("跳轉首頁面...");

        //第一次進入頁面
        driver.get("https://login.dingtalk.com/oauth2/challenge.htm?redirect_uri=https%3A%2F%2Foa.dingtalk.com%2Fomp%2Flogin%2Fdingtalk_sso_call_back%3Fcontinue%3Dhttps%253A%252F%252Foa.dingtalk.com&response_type=code&client_id=dingoaltcsv4vlgoefhpec&scope=openid+corpid&org_type=management");
        System.out.println("正在登錄...");

        //創建一個等待器,300秒后超時,每2秒檢查一次,有結果后直接返回,這里直接返回accessToken
        Cookie accessToken = new FluentWait<EdgeDriver>(driver)
                .withTimeout(Duration.ofSeconds(300))
                .pollingEvery(Duration.ofSeconds(2))
                .ignoring(NoSuchElementException.class)
                .until(edgeDriver -> {
                    Cookie access_token = driver.manage().getCookieNamed("access_token");
                    if (access_token == null) {
                        System.out.println("正在檢查正在登錄中...");
                    } else {
                        System.out.println("登錄成功!");
                    }
                    return access_token;
                });

        System.out.println("開始截圖");
        driver.navigate().to(String.format("https://aflow.dingtalk.com/dingtalk/web/query/oaDesigner?from=oaAdminHomeWeb&processCode=%s&tab=process", "PROC-B9DBBF95-3130-4DAC-8FB4-C1390C3C9E54"));
        //模擬窗口調小
        Map<String, Object> map = new HashMap<>();
        map.put("mobile", false);
        map.put("width", 300);
        map.put("height", 300);
        map.put("deviceScaleFactor", 1);
        driver.executeCdpCommand("Emulation.setDeviceMetricsOverride", map);
        //等待頁面元素.dingflow-design被載入
        WebElement dingflowDesign = new FluentWait<>(driver)
                .withTimeout(Duration.ofSeconds(300))
                .pollingEvery(Duration.ofSeconds(2))
                .ignoring(NoSuchElementException.class)
                .until(edgeDriver -> {
                    List<WebElement> elements = driver.findElements(By.className("dingflow-design"));
                    if (elements == null || elements.size() == 0) {
                        System.out.println("正在跳轉中...");
                        return null;
                    }
                    System.out.println("跳轉成功!");
                    return elements.get(0);
                });
        System.out.println("正在截圖...");
        Long width = (Long) driver.executeScript("return arguments[0].scrollWidth", dingflowDesign);
        Long height = (Long) driver.executeScript("return arguments[0].scrollHeight", dingflowDesign);
        map.clear();
        map.put("mobile", false);
        map.put("width", width + width / 10);
        map.put("height", height + height / 10);
        map.put("deviceScaleFactor", 1);
        driver.executeCdpCommand("Emulation.setDeviceMetricsOverride", map);
        File src = driver.getScreenshotAs(OutputType.FILE);
        String pngfileName = "D:\\edgedriver_win64\\testImage.png";
        FileUtils.copyFile(src, new File(pngfileName));
        FileUtils.copyFile(captureElement(src, dingflowDesign), new File(pngfileName));
        System.out.println("頁面截圖成功!");
        System.out.println("完成,退出!!");
        driver.quit();
    }

    /**
     * 根據元素生成圖片
     *
     * @param screenshot
     * @param element
     * @return
     */
    public static File captureElement(File screenshot, WebElement element) {
        try {
            BufferedImage img = ImageIO.read(screenshot);
            int width = element.getSize().getWidth();
            int height = element.getSize().getHeight();
            //獲取指定元素的坐標
            Point point = element.getLocation();
            //從元素左上角坐標開始,按照元素的高寬對img進行裁剪為符合需要的圖片
            BufferedImage dest = img.getSubimage(point.getX(), point.getY(), width, height);
            ImageIO.write(dest, "png", screenshot);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return screenshot;
    }
}

截圖成功

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM