提问人:James Hollingworth 提问时间:8/6/2010 最后编辑:Super Kai - Kazuya ItoJames Hollingworth 更新时间:9/15/2023 访问量:657780
如何使用 Selenium WebDriver 截屏?
How to take a screenshot with Selenium WebDriver?
答:
爪哇岛
是的,这是可能的。以下示例是用 Java 编写的:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
评论
/tmp
/tmp
HtmlUnitDriver
TakesScreenshot
org.apache.commons.io.FileUtils
蟒
每个 WebDriver 都有一个方法。所以对于Firefox来说,它可以这样使用:.save_screenshot(filename)
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://www.google.com/')
browser.save_screenshot('screenie.png')
令人困惑的是,还存在一种执行相同操作的方法。.get_screenshot_as_file(filename)
还有以下方法:(用于嵌入 HTML)和(用于检索二进制数据)。.get_screenshot_as_base64()
.get_screenshot_as_png()
请注意,WebElements 有一个类似的工作方法,但只捕获选定的元素。.screenshot()
评论
driver.set_window_size(1366, 728)
红宝石
require 'rubygems'
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :ie
driver.get "https://www.google.com"
driver.save_screenshot("./screen.png")
更多文件类型和选项可用,您可以在文件 takes_screenshot.rb 中看到它们。
评论
headless
Firefox
driver.save_screenshot
driver.get
爪哇岛
我解决了这个问题。您可以增强 ,为其提供其代理驱动程序实现的所有接口:RemoteWebDriver
WebDriver augmentedDriver = new Augmenter().augment(driver);
((TakesScreenshot)augmentedDriver).getScreenshotAs(...); // It works this way
评论
Java(机器人框架)
我用这种方法截屏。
void takeScreenShotMethod(){
try{
Thread.sleep(10000)
BufferedImage image = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "jpg", new File("./target/surefire-reports/screenshot.jpg"));
}
catch(Exception e){
e.printStackTrace();
}
}
您可以在需要时使用此方法。
评论
吉顿
import org.openqa.selenium.OutputType as OutputType
import org.apache.commons.io.FileUtils as FileUtils
import java.io.File as File
import org.openqa.selenium.firefox.FirefoxDriver as FirefoxDriver
self.driver = FirefoxDriver()
tempfile = self.driver.getScreenshotAs(OutputType.FILE)
FileUtils.copyFile(tempfile, File("C:\\screenshot.png"))
爪哇岛
public String captureScreen() {
String path;
try {
WebDriver augmentedDriver = new Augmenter().augment(driver);
File source = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
path = "./target/screenshots/" + source.getName();
FileUtils.copyFile(source, new File(path));
}
catch(IOException e) {
path = "Failed to capture screenshot: " + e.getMessage();
}
return path;
}
评论
PHP (PHPUnit)
它使用PHPUnit_Selenium扩展版本 1.2.7:
class MyTestClass extends PHPUnit_Extensions_Selenium2TestCase {
...
public function screenshot($filepath) {
$filedata = $this->currentScreenshot();
file_put_contents($filepath, $filedata);
}
public function testSomething() {
$this->screenshot('/path/to/screenshot.png');
}
...
}
评论
红宝石(黄瓜)
After do |scenario|
if(scenario.failed?)
puts "after step is executed"
end
time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M')
file_path = File.expand_path(File.dirname(__FILE__) + '/../../../../../mlife_screens_shot')+'/'+time +'.png'
page.driver.browser.save_screenshot file_path
end
Given /^snapshot$/ do
time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M')
file_path = File.expand_path(File.dirname(__FILE__) + '/../../../../../mlife_screens_shot')+'/'+time +'.png'
page.driver.browser.save_screenshot file_path
end
评论
C#
public Bitmap TakeScreenshot(By by) {
// 1. Make screenshot of all screen
var screenshotDriver = _selenium as ITakesScreenshot;
Screenshot screenshot = screenshotDriver.GetScreenshot();
var bmpScreen = new Bitmap(new MemoryStream(screenshot.AsByteArray));
// 2. Get screenshot of specific element
IWebElement element = FindElement(by);
var cropArea = new Rectangle(element.Location, element.Size);
return bmpScreen.Clone(cropArea, bmpScreen.PixelFormat);
}
红宝石
time = Time.now.strftime('%a_%e_%Y_%l_%m_%p_%M_%S')
file_path = File.expand_path(File.dirname(__FILE__) + 'screens_shot')+'/'+time +'.png'
#driver.save_screenshot(file_path)
page.driver.browser.save_screenshot file_path
JavaScript (Selenium-Webdriver)
driver.takeScreenshot().then(function(data){
var base64Data = data.replace(/^data:image\/png;base64,/,"")
fs.writeFile("out.png", base64Data, 'base64', function(err) {
if(err) console.log(err);
});
});
评论
var1
takeScreenshot()
C#
public void TakeScreenshot()
{
try
{
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
ss.SaveAsFile(@"D:\Screenshots\SeleniumTestingScreenshot.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
throw;
}
}
评论
爪哇岛
使用 RemoteWebDriver,在使用屏幕截图功能增强 Node 后,我会像这样存储屏幕截图:
void takeScreenShotMethod(){
try{
Thread.sleep(10000);
long id = Thread.currentThread().getId();
BufferedImage image = new Robot().createScreenCapture(new Rectangle(
Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "jpg", new File("./target/surefire-reports/"
+ id + "/screenshot.jpg"));
}
catch( Exception e ) {
e.printStackTrace();
}
}
您可以在需要时使用此方法。然后,我假设您可以在 surefire-reports/html/custom.css 中自定义 maven-surefire-report-plugin 的样式表,以便您的报告包含指向每个测试的正确屏幕截图的链接?
评论
PHP的
public function takescreenshot($event)
{
$errorFolder = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . "ErrorScreenshot";
if(!file_exists($errorFolder)){
mkdir($errorFolder);
}
if (4 === $event->getResult()) {
$driver = $this->getSession()->getDriver();
$screenshot = $driver->getWebDriverSession()->screenshot();
file_put_contents($errorFolder . DIRECTORY_SEPARATOR . 'Error_' . time() . '.png', base64_decode($screenshot));
}
}
评论
takescreenshot
$event
爪哇岛
这里似乎缺少 - 截取 Java 中特定元素的屏幕截图:
public void takeScreenshotElement(WebElement element) throws IOException {
WrapsDriver wrapsDriver = (WrapsDriver) element;
File screenshot = ((TakesScreenshot) wrapsDriver.getWrappedDriver()).getScreenshotAs(OutputType.FILE);
Rectangle rectangle = new Rectangle(element.getSize().width, element.getSize().height);
Point location = element.getLocation();
BufferedImage bufferedImage = ImageIO.read(screenshot);
BufferedImage destImage = bufferedImage.getSubimage(location.x, location.y, rectangle.width, rectangle.height);
ImageIO.write(destImage, "png", screenshot);
File file = new File("//path//to");
FileUtils.copyFile(screenshot, file);
}
评论
code
Firefox
中,它可以很好地工作,因为它可以根据尺寸从完整的图像中裁剪元素屏幕。在 Chrome
中,如果该元素在视图部分可用,而无需从该视图部分滚动图像,则可以很好地捕获元素。如果我们想在滚动两次客户端高度后截取屏幕截图,则可以使用以获取确切的元素屏幕截图。感谢您的这篇文章,因为它对我有帮助......document.documentElement.clientHeight
(location.y)-2*clientHeight
爪哇岛
我无法得到公认的答案,但根据当前的 WebDriver 文档,以下内容在 OS X v10.9 (Mavericks) 上使用 Java 7 对我来说效果很好:
import java.io.File;
import java.net.URL;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class Testing {
public void myTest() throws Exception {
WebDriver driver = new RemoteWebDriver(
new URL("http://localhost:4444/wd/hub"),
DesiredCapabilities.firefox());
driver.get("http://www.google.com");
// RemoteWebDriver does not implement the TakesScreenshot class
// if the driver does have the Capabilities to take a screenshot
// then Augmenter will add the TakesScreenshot methods to the instance
WebDriver augmentedDriver = new Augmenter().augment(driver);
File screenshot = ((TakesScreenshot)augmentedDriver).
getScreenshotAs(OutputType.FILE);
}
}
爪哇岛
String yourfilepath = "E:\\username\\Selenium_Workspace\\foldername";
// Take a snapshort
File snapshort_file = ((TakesScreenshot) mWebDriver)
.getScreenshotAs(OutputType.FILE);
// Copy the file into folder
FileUtils.copyFile(snapshort_file, new File(yourfilepath));
爪哇岛
public void captureScreenShot(String obj) throws IOException {
File screenshotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File("Screenshots\\" + obj + "" + GetTimeStampValue() + ".png"));
}
public String GetTimeStampValue()throws IOException{
Calendar cal = Calendar.getInstance();
Date time = cal.getTime();
String timestamp = time.toString();
System.out.println(timestamp);
String systime = timestamp.replace(":", "-");
System.out.println(systime);
return systime;
}
使用这两种方法,您还可以使用日期和时间截屏。
C# (Ranorex API)
public static void ClickButton()
{
try
{
// code
}
catch (Exception e)
{
TestReport.Setup(ReportLevel.Debug, "myReport.rxlog", true);
Report.Screenshot();
throw (e);
}
}
评论
硒犍
captureEntirePageScreenshot | /path/to/filename.png | background=#ccffdd
蟒
def test_url(self):
self.driver.get("https://www.google.com/")
self.driver.save_screenshot("test.jpg")
它将在保存脚本的同一目录中保存屏幕截图。
评论
C#
public static void TakeScreenshot(IWebDriver driver, String filename)
{
// Take a screenshot and save it to filename
Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
screenshot.SaveAsFile(filename, ImageFormat.Png);
}
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
评论
[OpenQA.Selenium.ScreenshotImageFormat]::Png
System.Drawing
您可以尝试 AShot API。它在 GitHub 上。
测试示例。
C#
using System;
using OpenQA.Selenium.PhantomJS;
using System.Drawing.Imaging;
namespace example.com
{
class Program
{
public static PhantomJSDriver driver;
public static void Main(string[] args)
{
driver = new PhantomJSDriver();
driver.Manage().Window.Size = new System.Drawing.Size(1280, 1024);
driver.Navigate().GoToUrl("http://www.example.com/");
driver.GetScreenshot().SaveAsFile("screenshot.png", ImageFormat.Png);
driver.Quit();
}
}
}
它需要 NuGet 包:It requires NuGet packages:
- 幻影JS2.0.0
- Selenium.Support 2.48.2
- Selenium.Web驱动程序 2.48.2
它已使用 .NET Framework v4.5.2 进行了测试。
C#
您可以使用以下代码片段/函数使用 Selenium 截取屏幕截图:
public void TakeScreenshot(IWebDriver driver, string path = @"output")
{
var cantakescreenshot = (driver as ITakesScreenshot) != null;
if (!cantakescreenshot)
return;
var filename = string.Empty + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond;
filename = path + @"\" + filename + ".png";
var ss = ((ITakesScreenshot)driver).GetScreenshot();
var screenshot = ss.AsBase64EncodedString;
byte[] screenshotAsByteArray = ss.AsByteArray;
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
ss.SaveAsFile(filename, ImageFormat.Png);
}
评论
爪哇岛
一种捕获 Selenium 中故障屏幕截图的方法,并附加了 TestName 和 Timestamp。
public class Screenshot{
final static String ESCAPE_PROPERTY = "org.uncommons.reportng.escape-output";
public static String imgname = null;
/*
* Method to Capture Screenshot for the failures in Selenium with TestName and Timestamp appended.
*/
public static void getSnapShot(WebDriver wb, String testcaseName) throws Exception {
try {
String imgpath = System.getProperty("user.dir").concat("\\Screenshot\\"+testcaseName);
File f = new File(imgpath);
if(!f.exists()) {
f.mkdir();
}
Date d = new Date();
SimpleDateFormat sd = new SimpleDateFormat("dd_MM_yy_HH_mm_ss_a");
String timestamp = sd.format(d);
imgname = imgpath + "\\" + timestamp + ".png";
// Snapshot code
TakesScreenshot snpobj = ((TakesScreenshot)wb);
File srcfile = snpobj.getScreenshotAs(OutputType.FILE);
File destFile = new File(imgname);
FileUtils.copyFile(srcfile, destFile);
}
catch(Exception e) {
e.getMessage();
}
}
通过 Selenium 的 Java 和 Python 客户端,有多种方法可以使用 Selenium WebDriver 截屏。
Java 方法
以下是截取屏幕截图的不同 Java 方法:
代码块:
package screenShot; 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; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class Firefox_takesScreenshot { public static void main(String[] args) throws IOException { System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.get("https://login.bws.birst.com/login.html/"); new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("Birst")); File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrFile, new File(".\\Screenshots\\Mads_Cruz_screenshot.png")); driver.quit(); } }
截图:
如果网页启用了 jQuery,则可以使用 pazone/ashot 库中的 ashot:
代码块:
package screenShot; import java.io.File; import javax.imageio.ImageIO; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import ru.yandex.qatools.ashot.AShot; import ru.yandex.qatools.ashot.Screenshot; import ru.yandex.qatools.ashot.shooting.ShootingStrategies; public class ashot_CompletePage_Firefox { public static void main(String[] args) throws Exception { System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.get("https://jquery.com/"); new WebDriverWait(driver, 20).until(ExpectedConditions.titleContains("jQuery")); Screenshot myScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver); ImageIO.write(myScreenshot.getImage(),"PNG",new File("./Screenshots/firefoxScreenshot.png")); driver.quit(); } }
截图:
代码块:
package screenShot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import com.assertthat.selenium_shutterbug.core.Shutterbug; import com.assertthat.selenium_shutterbug.utils.web.ScrollStrategy; public class selenium_shutterbug_fullpage_firefox { public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); driver.get("https://www.google.co.in"); Shutterbug.shootPage(driver, ScrollStrategy.BOTH_DIRECTIONS).save("./Screenshots/"); driver.quit(); } }
截图:
Python 方法
以下是用于截取屏幕截图的不同 Python 方法:
使用
save_screenshot()
方法:代码块:
from selenium import webdriver driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe') driver.get("http://google.com") driver.save_screenshot('./Screenshots/save_screenshot_method.png') driver.quit()
截图:
使用
get_screenshot_as_file()
方法:代码块:
from selenium import webdriver driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe') driver.get("http://google.com") driver.get_screenshot_as_file('./Screenshots/get_screenshot_as_file_method.png') driver.quit()
截图:
使用
get_screenshot_as_png()
方法:代码块:
from selenium import webdriver driver = webdriver.Chrome(r'C:\Utility\BrowserDrivers\chromedriver.exe') driver.get("http://google.com") screenPnG = driver.get_screenshot_as_png() # Crop it back to the window size (it may be taller) box = (0, 0, 1366, 728) im = Image.open(BytesIO(screenPnG)) region = im.crop(box) region.save('./Screenshots/get_screenshot_as_png_method.png', 'PNG', optimize=True, quality=95) driver.quit()
截图:
更新时间:2022
为了在 Selenium 中截取屏幕截图,我们使用一个名为 的接口,它使 Selenium WebDriver 能够捕获屏幕截图并以不同的方式存储它。它有一个捕获屏幕截图并将其存储在指定位置的方法。TakesScreenshot
getScreenshotAs()
//Convert webdriver to TakeScreenshot
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
在上面的代码中,它将 WebDriver 对象(驱动程序)转换为 TakeScreenshot。并调用方法通过提供参数来创建图像文件getScreenshotAs()
*OutputType.FILE.
我们可以使用 File 对象将图像复制到我们想要的位置,如下所示,使用 .FileUtils Class
FileUtils.copyFile(screenshotFile , new File("C:\\temp\\screenshot.png));
捕获整个页面
Selenium WebDriver 不提供捕获整个页面屏幕截图的固有功能。要捕获整页屏幕截图,我们必须使用名为 Ashot 的第三方库。它提供了对特定 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 毫秒滚动一次以截取屏幕截图。
捕获 elememnt
有两种方法可以在 Selenium 中捕获 Web 元素的屏幕截图。
- 获取全屏图像,然后根据 Web 元素的尺寸裁剪图像。
- 在 Web 元素上使用方法。(这仅在 selenium 版本 4.X 中可用)
getScreenshotAs()
评论