是否有人知道是否可以使用Selenium WebDriver截取屏幕截图? (注意:不是Selenium RC)
答案 0 :(得分:472)
是的,有可能。以下示例使用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"));
答案 1 :(得分:238)
每个WebDriver都有.save_screenshot(filename)
方法。因此对于Firefox,它可以像这样使用:
from selenium import webdriver
browser = webdriver.Firefox()
browser.get('http://www.google.com/')
browser.save_screenshot('screenie.png')
令人困惑的是,.get_screenshot_as_file(filename)
方法也存在同样的事情。
还有以下方法:.get_screenshot_as_base64()
(用于嵌入html)和.get_screenshot_as_png()
(用于检索二进制数据)。
并注意WebElements有一个.screenshot()
方法,它的工作方式类似,但只捕获所选元素。
答案 2 :(得分:98)
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;
}
}
答案 3 :(得分:63)
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);
});
});
答案 4 :(得分:61)
require 'rubygems'
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :ie
driver.get "https://www.google.com"
driver.save_screenshot("./screen.png")
可以使用更多文件类型和选项,您可以在takes_screenshot.rb
中查看它们答案 5 :(得分:34)
我解决了这个问题。您可以扩充RemoteWebDriver
以为其代理驱动程序实现的所有接口提供:
WebDriver augmentedDriver = new Augmenter().augment(driver);
((TakesScreenshot)augmentedDriver).getScreenshotAs(...); //works this way
答案 6 :(得分:33)
使用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');
}
...
}
答案 7 :(得分:23)
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);
}
答案 8 :(得分:18)
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;
}
答案 9 :(得分:12)
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"))
答案 10 :(得分:9)
我用这种方法进行屏幕截图。
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();
}
}
您可以在需要的地方使用此方法。
答案 11 :(得分:8)
这里似乎缺少 - 在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);
}
答案 12 :(得分:6)
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();
}
}
}
需要NuGetPackages:
使用.NETFramework v4.5.2进行测试
答案 13 :(得分:5)
我无法获得已接受的工作答案,但按照the current WebDriver documentation,在OS X 10.9上使用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);
}
}
答案 14 :(得分:4)
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
答案 15 :(得分:4)
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
答案 16 :(得分:4)
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));
}
}
答案 17 :(得分:4)
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
答案 18 :(得分:3)
使用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的样式表,以便您的报告包含每个测试的正确屏幕截图的链接?
答案 19 :(得分:3)
答案 20 :(得分:3)
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);
}
答案 21 :(得分:2)
captureEntirePageScreenshot | /path/to/filename.png | background=#ccffdd
答案 22 :(得分: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);
}
答案 23 :(得分:2)
<强> JAVA 强>
捕获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();
}
}
答案 24 :(得分:2)
Python-元素的屏幕截图:
这是一个很老的问题,有多个答案。但是,这里似乎缺少使用Python拍摄特定Web元素的屏幕截图。
位置
Web元素在页面上具有自己的位置,通常以x和y像素为单位进行度量,称为元素的(x,y)坐标。位置对象包含两个值。
大小
就像位置一样,每个WebElement都有宽度和高度;可用作尺寸对象。
使用(x,y)坐标和宽度,高度值,我们可以裁剪图像并将其存储在文件中。
from selenium import webdriver
from PIL import Image
driver = webdriver.Firefox(executable_path='[Browser Driver Path]');
driver.get('https://www.google.co.in');
element = driver.find_element_by_xpath("//div[@id='hplogo']");
location = element.location;
size = element.size;
driver.save_screenshot("/data/image.png");
x = location['x'];
y = location['y'];
width = location['x']+size['width'];
height = location['y']+size['height'];
im = Image.open('/data/WorkArea/image.png')
im = im.crop((int(x), int(y), int(width), int(height)))
im.save('/data/image.png')
注意: 摘自http://allselenium.info/capture-screenshot-element-using-python-selenium-webdriver/
答案 25 :(得分:2)
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;
}
使用这两种方法,您也可以拍摄日期和时间的屏幕截图。
答案 26 :(得分:2)
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));
希望这能解决您的问题
答案 27 :(得分:2)
您可以使用python web驱动程序从Windows捕获图像。使用下面的代码需要捕获屏幕截图
driver.save_screenshot('c:\foldername\filename.extension(png,jpeg)')
答案 28 :(得分:1)
def test_url(self):
self.driver.get("https://www.google.com/")
self.driver.save_screenshot("test.jpg")
它会将截屏保存在保存脚本的同一目录中。
答案 29 :(得分:1)
以下是Selenide项目的工作方式,比其他任何方式更容易:
import static com.codeborne.selenide.Selenide.screenshot;
screenshot("my_file_name");
对于Junit:
@Rule
public ScreenShooter makeScreenshotOnFailure =
ScreenShooter.failedTests().succeededTests();
对于TestNG:
import com.codeborne.selenide.testng.ScreenShooter;
@Listeners({ ScreenShooter.class})
答案 30 :(得分:1)
以为我会提供完整的解决方案,因为有两种不同的方式来获取屏幕截图。一个来自本地浏览器,一个来自远程浏览器。我甚至将图像嵌入到html报告中
@After()
public void selenium_after_step(Scenario scenario) throws IOException, JSONException {
if (scenario.isFailed()){
scenario.write("Current URL = " + driver.getCurrentUrl() + "\n");
try{
driver.manage().window().maximize(); //Maximize window to get full screen for chrome
}catch (org.openqa.selenium.WebDriverException e){
System.out.println(e.getMessage());
}
try {
if(isAlertPresent()){
Alert alert = getAlertIfPresent();
alert.accept();
}
byte[] screenshot;
if(false /*Remote Driver flow*/) { //Get Screen shot from remote driver
Augmenter augmenter = new Augmenter();
TakesScreenshot ts = (TakesScreenshot) augmenter.augment(driver);
screenshot = ts.getScreenshotAs(OutputType.BYTES);
} else { //get screen shot from local driver
//local webdriver user flow
screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
}
scenario.embed(screenshot, "image/png"); //Embed image in reports
} catch (WebDriverException wde) {
System.err.println(wde.getMessage());
} catch (ClassCastException cce) {
cce.printStackTrace();
}
}
//seleniumCleanup();
}
答案 31 :(得分:1)
public static void ClickButton()
{
try
{
// code
}
catch (Exception e)
{
TestReport.Setup(ReportLevel.Debug, "myReport.rxlog", true);
Report.Screenshot();
throw (e);
}
}
答案 32 :(得分:1)
以下是使用Robot Framework和Selenium2Library:
的解决方案*** Settings ***
Library Selenium2Library
*** Test Cases ***
Example
Open Browser http://localhost:8080/index.html firefox
Capture Page Screenshot
这将在工作空间中保存屏幕截图。也可以为关键字Capture Page Screenshot
提供文件名以更改该行为。
答案 33 :(得分:1)
您可以使用webdriverbacked selenium object
类对象创建Webdriver
,然后您可以进行截屏。
答案 34 :(得分:0)
使用 C# 和 MSTestframework, 这里我创建了一个静态方法。采取了一个路径,我可以将图像存储为 jpeg 格式。为了更清楚,我用当前的执行测试用例以及失败的日期和时间来命名这些屏幕截图。
/// <summary>
/// This method is used to screen shot where test method failed
/// </summary>
/// <param name="testCase">TestCaseName</param>
public static void Capture(string testCase)
{
try
{
StringBuilder path = new StringBuilder("C:/Logs/Screenshot/");
Constant.screenshot = ((ITakesScreenshot)Constant.browser).GetScreenshot();
string fileName = path.Append(string.Format(testCase + "-at-{0:yyyy-MM dd_hh-mm-ss}.jpeg", DateTime.Now)).ToString();
Constant.screenshot.SaveAsFile(fileName, ScreenshotImageFormat.Jpeg);
}
catch (Exception e)
{
File.AppendAllText("C:/Logs/FailedTestCasesLogs.txt", "\nCOULD NOT CAPTURE THE SCREENSHOT!\n");
Log(e);
}
}
答案 35 :(得分:0)
/**
* Take a screenshot and move to the given folder location.
*
* @param driver
* @param folderLocation
* @return screenShotFilePath
*/
public static String captureScreenshot(WebDriver driver, String folderLocation) {
// Variable to store screenshot's file path.
String screenShotFilePath = null;
// Generate unique id for screen shot name.
String uniqueId = UUID.randomUUID().toString().substring(31);
if (driver != null) {
// Generate screenshot as a file
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// New screenshot file path with having file name
screenShotFilePath = folderLocation + File.separator + uniqueId + ".png";
// Move file to the destination location.
FileUtils.moveFile(scrFile, new File(screenShotFilePath));
}
return screenShotFilePath;
}
答案 36 :(得分:0)
对于Java的较新版本, FileUtils 功能不起作用。在这里,以下功能非常适合复制屏幕截图。
import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.io.FileHandler;
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
File destfile = new File(destination folder /filename.extension);
FileHandler.copy(scrfile, destfile);
答案 37 :(得分:0)
是的,可以通过Selenium Web Driver
截屏。我目前使用Chrome Driver
捕捉网站图像。请参考以下方法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();
答案 38 :(得分:0)
<强>的Python 强>
webdriver.get_screenshot_as_file(filepath)
上述方法将截取屏幕截图,并将其作为文件存储在作为参数提供的位置。
答案 39 :(得分:0)
是的,可以使用Selenium WebDriver拍摄网页快照。
WebDriver API提供的 getScreenshotAs()
方法为我们工作。
语法: getScreenshotAs(OutputType<X> target)
返回类型: X
参数: target
- 检查OutputType
提供的选项
适用性:并非特定于任何DOM元素
示例:强>
TakesScreenshot screenshot = (TakesScreenshot) driver;
File file = screenshot.getScreenshotAs(OutputType.FILE);
有关详细信息,请参阅下面的工作代码段。
public class TakeScreenShotDemo {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get(“http: //www.google.com”);
TakesScreenshot screenshot = (TakesScreenshot) driver;
File file = screenshot.getScreenshotAs(OutputType.FILE);
// creating a destination file
File destination = new File(“newFilePath(e.g.: C: \\Folder\\ Desktop\\ snapshot.png)”);
try {
FileUtils.copyFile(file, destination);
} catch (IOException e) {
e.printStackTrace();
}
}
}
访问:Snapshot using WebDriver了解详情。
答案 40 :(得分:0)
C#代码
IWebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((ITakesScreenshot)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"));
答案 41 :(得分:0)
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();
}
}
答案 42 :(得分:0)
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");
答案 43 :(得分:0)
import java.io.File;
import java.io.IOException;
import org.apache.maven.surefire.shade.org.apache.maven.shared.utils.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
/**
* @author Jagdeep Jain
*
*/
public class ScreenShotMaker {
// take screen shot on the test failures
public void takeScreenShot(WebDriver driver, String fileName) {
File screenShot = ((TakesScreenshot) driver)
.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenShot, new File("src/main/webapp/screen-captures/" + fileName + ".png"));
} catch (IOException ioe) {
throw new RuntimeException(ioe.getMessage(), ioe);
}
}
}
答案 44 :(得分:0)
我在C#中使用以下代码来获取整页或仅使用浏览器屏幕截图
public void screenShot(string tcName)
{
try
{
string dateTime = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
string screenShotName = @"D:\Selenium\Project\VAM\VAM\bin" + "\\" + tcName + dateTime + ".png";
ITakesScreenshot screen = driverScript.driver as ITakesScreenshot;
Screenshot screenshot = screen.GetScreenshot();
screenshot.SaveAsFile(screenShotName, System.Drawing.Imaging.ImageFormat.Png);
if (driverScript.last == 1)
this.writeResult("Sheet1", "Fail see Exception", "Status", driverScript.resultRowID);
}
catch (Exception ex)
{
driverScript.writeLog.writeLogToFile(ex.ToString(), "inside screenShot");
}
}
public void fullPageScreenShot(string tcName)
{
try
{
string dateTime = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now);
string screenShotName = @"D:\Selenium\Project\VAM\VAM\bin" + "\\" + tcName + dateTime + ".png";
Rectangle bounds = Screen.GetBounds(Point.Empty);
using (Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height))
{
using (Graphics g = Graphics.FromImage(bitmap))
{
g.CopyFromScreen(Point.Empty, Point.Empty, bounds.Size);
}
bitmap.Save(screenShotName, System.Drawing.Imaging.ImageFormat.Png);
}
if (driverScript.last == 1)
this.writeResult("Sheet1", "Pass", "Status", driverScript.resultRowID);
}
catch (Exception ex)
{
driverScript.writeLog.writeLogToFile(ex.ToString(), "inside fullPageScreenShot");
}
}