如何在Chrome浏览器中的selenium webdriver中截图

pw9qyyiw  于 2023-09-28  发布在  Go
关注(0)|答案(2)|浏览(105)

我在学习selenium Webdriver。我试图在Chrome浏览器上截图,但我得到了以下代码的例外(注:同样的代码也可以在Firefox上运行)。请帮助我在Chrome上截图,请有人解释我为什么下面的代码在Chrome上不起作用。

public class ScreenShot 
{
    public static void main(String[] args) throws IOException 
    {
        String key  = "webdriver.chrome.driver";
        String value = "./driver/chromedriver.exe";
        System.setProperty(key, value);
        WebDriver driver = new ChromeDriver();
        driver.get("https://www.google.co.in");
        TakesScreenshot screen = (TakesScreenshot) driver;
        File srcFile = screen.getScreenshotAs(OutputType.FILE);
        File destFile = new File("d:/google.png");
        FileUtils.copyFile(srcFile, destFile);
    }
}
piah890a

piah890a1#

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public static String captureScreenshot (WebDriver driver, String screenshotName){

    try {
        TakesScreenshot ts = (TakesScreenshot)driver;
        File source = ts.getScreenshotAs(OutputType.FILE);
        String dest = "/Users/CD6255ABQA/Desktop/Debug Images/" + screenshotName + ".png";
        File destination = new File(dest);
        FileUtils.copyFile(source, destination);
        return dest;
        } 

    catch (IOException e) {return e.getMessage();}
    }

称之为利用

String screenpath = captureScreenshot(driver, "ScreenshotName")

请记住在方法中更改文件目标。

kmpatx3s

kmpatx3s2#

在Django(Python)中,您可以在无头Google Chrome上截取Django Admin的屏幕截图,如下所示。* 我使用pytest-djangoselenium,我的答案解释了更多:

import pytest
from selenium import webdriver

def take_screenshot(driver, name):
    os.makedirs(os.path.join("screenshot", os.path.dirname(name)), exist_ok=True)
    driver.save_screenshot(os.path.join("screenshot", name))

def test_1(live_server):
    options = webdriver.ChromeOptions()
    options.add_argument("--headless=new")
    driver = webdriver.Chrome(options=options)
    driver.set_window_size(1024, 768)
    driver.get(("%s%s" % (live_server.url, "/admin/")))
    take_screenshot(driver, "admin/chrome.png")
    assert "Log in | Django site admin" in driver.title

相关问题