How to get screenshot of full webpage using Selenium and Java?

前端 未结 9 729
耶瑟儿~
耶瑟儿~ 2020-12-29 08:17

How to take a screenshot of the entire web page (full-page screenshot), not only partial (top-to-bottom) using Selenium WebDriver?

My code:

9条回答
  •  天命终不由人
    2020-12-29 08:55

    For some pages I neeed to take screenshot of begin and end of page. So I use to take 2 screenshots:

    public static String javaIoTmpDir = System.getProperty("java.io.tmpdir"); //tmp dir
    //create screenshot
        driver.manage().window().fullscreen();
        //For large pages - body over 850 px highh - take addition screenshot of the end of page
        if (driver.findElements(By.id("panel_body")).size()>0) {
            WebElement body = driver.findElement(By.id("panel_body"));
            int bodyHight = body.getSize().getHeight();
            if (bodyHight > 850) {
                Robot robot = new Robot();
                robot.keyPress(KeyEvent.VK_END);
                robot.keyRelease(KeyEvent.VK_END);
                Thread.sleep(1000);
                File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
                String timePictureEnd = javaIoTmpDir+"\\scr_"+String.valueOf(System.currentTimeMillis())+getClass().toString().substring(getClass().toString().lastIndexOf(".qa.")+3)+".png";
                FileUtils.copyFile(scrFile, new File(timePictureEnd));
                robot.keyPress(KeyEvent.VK_HOME); //back to top page for next screen
                robot.keyRelease(KeyEvent.VK_HOME);
                Thread.sleep(1000);
            }
        }
        String timePicture = javaIoTmpDir+"\\scr_"+String.valueOf(System.currentTimeMillis())+getClass().toString().substring(getClass().toString().lastIndexOf(".qa.")+3)+".png";
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(scrFile, new File(timePicture));
    

提交回复
热议问题