是否可以使用Selenium WebDriver进行截图?

(注:不含硒遥控器)


当前回答

是的,可以通过Selenium WebDriver来截屏。我目前使用Chrome驱动来抓取网站图片。请参考以下方法captureScreenshot()。

您还可以添加对web驱动程序的限制,例如

使用无头版的网页浏览器 当页面加载时禁用通知 启动全屏等。

如果一个网站配备了警报框,你的网页驱动程序将无法捕捉屏幕截图,因为异常将被抛出。在这种情况下,你需要关闭警告框,然后获取截图。下面的代码片段关闭警报框。

    public void captureScreenshot() throws InterruptedException, IOException {

        System.out.println("Creating Chrome Driver");

        // Set Chrome Driver
        System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe");

        // Add arguments to Chrome Options
        ChromeOptions chromeOptions = new ChromeOptions();
        chromeOptions.addArguments("--headless");
        chromeOptions.addArguments("start-maximized");
        chromeOptions.addArguments("--disable-gpu");
        chromeOptions.addArguments("--start-fullscreen");
        chromeOptions.addArguments("--disable-extensions");
        chromeOptions.addArguments("--disable-popup-blocking");
        chromeOptions.addArguments("--disable-notifications");
        chromeOptions.addArguments("--window-size=1920,1080");
        chromeOptions.addArguments("--no-sandbox");
        chromeOptions.addArguments("--dns-prefetch-disable");
        chromeOptions.addArguments("enable-automation");
        chromeOptions.addArguments("disable-features=NetworkService");

        WebDriver driver = new ChromeDriver(chromeOptions);
        driver.get("https://www.google.com");
        System.out.println("Wait a bit for the page to render");
        TimeUnit.SECONDS.sleep(5);
        System.out.println("Taking Screenshot");
        File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        String imageDetails = "D:\\Images";
        File screenShot = new File(imageDetails).getAbsoluteFile();
        FileUtils.copyFile(outputFile, screenShot);
        System.out.println("Screenshot saved: {}" + imageDetails);
    }
}

为了接受警报框和获取截图:

String alertText = alert.getText();
System.out.println("ERROR: (ALERT BOX DETECTED) - ALERT MSG : " + alertText);
alert.accept();
File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String imageDetails = "D://Images"
File screenShot = new File(imageDetails).getAbsoluteFile();
FileUtils.copyFile(outputFile, screenShot);
System.out.println("Screenshot saved: {}" + imageDetails);
driver.close();

其他回答

Python

def test_url(self):
    self.driver.get("https://www.google.com/")
    self.driver.save_screenshot("test.jpg")

它将在脚本保存的同一目录下保存一个截图。

PowerShell

Set-Location PATH:\to\selenium

Add-Type -Path "Selenium.WebDriverBackedSelenium.dll"
Add-Type -Path "ThoughtWorks.Selenium.Core.dll"
Add-Type -Path "WebDriver.dll"
Add-Type -Path "WebDriver.Support.dll"

$driver = New-Object OpenQA.Selenium.PhantomJS.PhantomJSDriver

$driver.Navigate().GoToUrl("https://www.google.co.uk/")

# Take a screenshot and save it to filename
$filename = Join-Path (Get-Location).Path "01_GoogleLandingPage.png"
$screenshot = $driver.GetScreenshot()
$screenshot.SaveAsFile($filename, [System.Drawing.Imaging.ImageFormat]::Png)

其他司机……

$driver = New-Object OpenQA.Selenium.Chrome.ChromeDriver
$driver = New-Object OpenQA.Selenium.Firefox.FirefoxDriver
$driver = New-Object OpenQA.Selenium.IE.InternetExplorerDriver
$driver = New-Object OpenQA.Selenium.Opera.OperaDriver

更新2022

要在Selenium中截取屏幕截图,我们使用一个名为TakesScreenshot的接口,它使Selenium WebDriver能够捕捉屏幕截图并以不同的方式存储它。它有一个getScreenshotAs()方法,用于捕获屏幕截图并将其存储在指定的位置。

//Convert webdriver to TakeScreenshot
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

在上面的代码中,它将WebDriver对象(驱动程序)转换为TakeScreenshot。并调用getScreenshotAs()方法通过提供参数*OutputType.FILE来创建图像文件。

我们可以使用File对象将图像复制到我们想要的位置,如下所示,使用FileUtils类。

FileUtils.copyFile(screenshotFile , new File("C:\\temp\\screenshot.png));

捕获整个页面

Selenium WebDriver没有提供捕获整个页面截图的固有功能。为了捕获整个页面的截图,我们必须使用一个名为shot的第三方库。它提供了截取特定WebElement的截图以及整页截图的功能。

捕获屏幕大小的图像

Screenshot screenshot = new Ashot().takeScreenshot(driver);

捕获整个页面的截图

Screenshot s=new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
ImageIO.write(s.getImage(),"PNG",new File("<< file path>>"));

在上面的代码中,1000是以毫秒为单位的滚动时间。换句话说,这意味着该程序将滚动每1000毫秒来截取屏幕截图。

捕获一个元素

在Selenium中有两种方法来捕获web元素的屏幕截图。

取全屏图像,然后根据网页元素的尺寸裁剪图像。 在web元素上使用getScreenshotAs()方法。(这只在selenium版本4.X中可用)

File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
BufferedImage originalImage = ImageIO.read(scrFile);
//int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
BufferedImage resizedImage = CommonUtilities.resizeImage(originalImage, IMG_HEIGHT, IMG_WIDTH);
ImageIO.write(resizedImage, "jpg", new File(path + "/"+ testCaseId + "/img/" + index + ".jpg"));
Image jpeg = Image.getInstance(path + "/" + testCaseId + "/img/"+ index + ".jpg");
public static void getSnapShot(WebDriver driver, String event) {

    try {
        File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
        BufferedImage originalImage = ImageIO.read(scrFile);
        //int type = originalImage.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : originalImage.getType();
        BufferedImage resizedImage = CommonUtilities.resizeImage(originalImage, IMG_HEIGHT, IMG_WIDTH);
        ImageIO.write(resizedImage, "jpg", new File(path + "/"+ testCaseId + "/img/" + index + ".jpg"));
        Image jpeg = Image.getInstance(path + "/" + testCaseId + "/img/"+ index + ".jpg");
        jpeg.setAlignment(Image.MIDDLE);
        PdfPTable table = new PdfPTable(1);
        PdfPCell cell1 = new PdfPCell(new Paragraph("\n"+event+"\n"));
        PdfPCell cell2 = new PdfPCell(jpeg, false);
        table.addCell(cell1);
        table.addCell(cell2);
        document.add(table);
        document.add(new Phrase("\n\n"));
        //document.add(new Phrase("\n\n" + event + "\n\n"));
        //document.add(jpeg);
        fileWriter.write("<pre>        " + event + "</pre><br>");
        fileWriter.write("<pre>        " + Calendar.getInstance().getTime() + "</pre><br><br>");
        fileWriter.write("<img src=\".\\img\\" + index + ".jpg\" height=\"460\" width=\"300\"  align=\"middle\"><br><hr><br>");
        ++index;
    }
    catch (IOException | DocumentException e) {
        e.printStackTrace();
    }
}