如何使用selenium在chrome中获取整页截图

时间:2018-01-11 06:41:31

标签: eclipse selenium

在selenium工具中,如何获取整页截图以及如何滚动页面? 如果我们使用此代码,

JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(0, document.body.scrollHeight)");

它直接移动到页面底部。

3 个答案:

答案 0 :(得分:0)

为此,我们需要下载ashot.jar文件并将其与selenium jar文件一起添加到项目中

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;

import javax.imageio.ImageIO;
import java.io.File;

public class TakeFullPageScreenShot
{
   public static void main(String args[]) throws Exception
   {
       System.setProperty("webdriver.gecko.driver",     "D:\\Selenium\\geckodriver.exe");
   WebDriver driver = new FirefoxDriver();

   driver.get("http://automationtesting.in/");
   Thread.sleep(2000);

   Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
   ImageIO.write(screenshot.getImage(),"PNG",new                              
File(System.getProperty("user.dir") +"/ErrorScreenshots/FullPageScreenshot.png"));
 }
}

它会将页面滚动到最后并捕获屏幕截图。我们可以使用viewportPasting方法控制滚动速度。

希望有所帮助

答案 1 :(得分:0)

Use the jar file of shutterbug in selenium. Here you can download the file : http://book2s.com/java/jar/s/selenium-shutterbug/download-selenium-shutterbug-0.4.html

And here is the command that will be placed in your code:

Shutterbug.shootPage(driver, ScrollStrategy.BOTH_DIRECTIONS).save("path to save image");

You dont need to handle any scrolls this is going to automatically capture full page screenshot

答案 2 :(得分:0)

System.setProperty("webdriver.chrome.driver", "F:\\chromedriver.exe"); 

ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);   
String baseUrl = "https://www.google.co.in";

driver.get(baseUrl);        
String fullscreen =Keys.chord(Keys.F11);
driver.findElement(By.cssSelector("body")).sendKeys(fullscreen);

TakesScreenshot scrShot =((TakesScreenshot)driver);  
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);   
File DestFile=new File("F://test.png");  
FileUtils.copyFile(SrcFile, DestFile);   
driver.close();