How to take screenshot with Selenium WebDriver
有人知道是否可以使用Selenium WebDriver截图吗?(注:不含硒RC)
爪哇
是的,这是可能的。下面的例子是在Java中:
1 2 3 4 5 | 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")); |
Python
每个WebDriver都有一个
1 2 3 4 5 | from selenium import webdriver browser = webdriver.Firefox() browser.get('http://www.google.com/') browser.save_screenshot('screenie.png') |
令人困惑的是,也存在一个执行相同操作的
还有一些方法用于:
请注意,webelements有一个与之类似的
C.*
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; } } |
javascript(Selenium WebDriver)
1 2 3 4 5 6 | 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); }); }); |
红宝石
1 2 3 4 5 6 | require 'rubygems' require 'selenium-webdriver' driver = Selenium::WebDriver.for :ie driver.get"https://www.google.com" driver.save_screenshot("./screen.png") |
有更多的文件类型和选项可用,您可以在takes_screenshot.rb中看到它们。
爪哇
我解决了这个问题。您可以增加
1 2 | WebDriver augmentedDriver = new Augmenter().augment(driver); ((TakesScreenshot)augmentedDriver).getScreenshotAs(...); //works this way |
PHP(PHPUnter)
使用phpunit_Selenium扩展版1.2.7:
1 2 3 4 5 6 7 8 9 10 11 12 | 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'); } ... } |
C.*
1 2 3 4 5 6 7 8 9 10 11 | 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); } |
爪哇
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; } |
杰森
1 2 3 4 5 6 7 8 | 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")) |
Java(机器人框架)
我用这种方法拍截图。
1 2 3 4 5 6 7 8 9 10 | 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(); } } |
您可以在需要时使用此方法。
爪哇
这里似乎缺少了——在Java中截取一个特定元素的截图:
1 2 3 4 5 6 7 8 9 10 11 | 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); } |
C.*
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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进行测试
爪哇
我无法得到公认的工作答案,但根据当前的WebDever文档,以下工作对我来说,在OS X 10.9上使用Java 7是很好的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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); } } |
红宝石
1 2 3 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 |
露比(黄瓜)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 |
动力壳
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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) |
其他驱动程序…
1 2 3 4 | $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 |
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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)); } } |
C.*
1 2 3 4 5 6 | 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); } |
您可以尝试一下Ashot API。这是Github链接。
https://github.com/yandex-qtools/ashot
这里的一些测试…
https://github.com/yandex-qatools/ashot/tree/master/src/test/java/ru/yandex/qatools/elementscompare/tests/测试
硒的
1 | captureEntirePageScreenshot | /path/to/filename.png | background=#ccffdd |
爪哇
使用RemoteWebDriver,在使用屏幕截图功能增强节点之后,我将像这样存储屏幕截图:
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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插件的样式表,以便您的报告包含指向每个测试的正确屏幕截图的链接?
Python
您可以使用python web驱动程序从Windows捕获图像。使用下面的代码,页面需要捕获屏幕截图
1 | driver.save_screenshot('c:\foldername\filename.extension(png,jpeg)') |
C.*
您可以使用以下代码段/函数对Selenium进行截图:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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); } |
爪哇
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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; } |
使用这两种方法,您还可以拍摄日期和时间的屏幕截图。
python-元素截图:
这是一个相当古老的问题,有多种答案。但是,这里似乎缺少使用python对特定web元素进行截屏的功能。
位置
一个web元素在页面上有自己的位置,通常以x和y像素来度量,称为元素的(x,y)坐标。位置对象包含两个值。
大小
与位置类似,每个WebElement都有宽度和高度;可用作大小对象。
使用(x,y)坐标和宽度、高度值,我们可以裁剪图像并将其存储在文件中。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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/
爪哇
1 2 3 4 5 6 7 8 | 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)); |
希望这能解决你的问题
爪哇
方法捕获Selenium中失败的屏幕截图,并附加testname和timestamp。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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(); } } |
Python
1 2 3 | def test_url(self): self.driver.get("https://www.google.com/") self.driver.save_screenshot("test.jpg") |
它将屏幕截图保存在保存脚本的同一目录中。
爪哇
我想我会给出完整的解决方案,因为有两种不同的截屏方式。一个来自本地浏览器,另一个来自远程浏览器。我甚至把图像嵌入到HTML报告中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | @After() public void selenium_after_step(Scenario scenario) throws IOException, JSONException { if (scenario.isFailed()){ scenario.write("Current URL =" + driver.getCurrentUrl() +" "); 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(); } |
硒化物/爪哇
以下是Selenide项目的工作原理,比其他任何方式都简单:
1 2 | import static com.codeborne.selenide.Selenide.screenshot; screenshot("my_file_name"); |
Junit:
1 2 3 | @Rule public ScreenShooter makeScreenshotOnFailure = ScreenShooter.failedTests().succeededTests(); |
TestNG:
1 2 | import com.codeborne.selenide.testng.ScreenShooter; @Listeners({ ScreenShooter.class}) |
机器人框架
下面是一个使用机器人框架和Selenium2库的解决方案:
1 2 3 4 5 6 7 | *** Settings *** Library Selenium2Library *** Test Cases *** Example Open Browser http://localhost:8080/index.html firefox Capture Page Screenshot |
这将在工作空间中保存一个屏幕截图。也可以向关键字
可以使用
C(Ranorex API)
1 2 3 4 5 6 7 8 9 10 11 12 13 | public static void ClickButton() { try { // code } catch (Exception e) { TestReport.Setup(ReportLevel.Debug,"myReport.rxlog", true); Report.Screenshot(); throw (e); } } |
使用Selenium WebDriver截图有多种方法
Java方法下面是不同的Java方法进行截图:
使用takesscreenshot接口中的
getScreenshotAs() :代码块:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26package 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:
代码块:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26package 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();
}
}截图:
使用断言中的Selenium Shutterbug/Selenium Shutterbug库:
代码块:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18package 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
1 | webdriver.get_screenshot_as_file(filepath) |
上述方法将截图并将其作为文件存储在作为参数提供的位置。
是的,可以使用Selenium WebDriver拍摄网页快照。
webdriver api提供的
语法:
返回类型:
参数:
适用性:不特定于任何DOM元素
例子:
1 2 | TakesScreenshot screenshot = (TakesScreenshot) driver; File file = screenshot.getScreenshotAs(OutputType.FILE); |
有关详细信息,请参阅下面的工作代码段。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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(); } } } |
访问:使用WebDriver获取更多详细信息。
C码
1 2 3 4 5 | 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")); |
1 2 3 4 5 6 | 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"); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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); } } } |
我在C中使用以下代码获取整个页面或仅浏览屏幕截图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 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"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | 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(" "+event+" ")); PdfPCell cell2 = new PdfPCell(jpeg, false); table.addCell(cell1); table.addCell(cell2); document.add(table); document.add(new Phrase(" ")); //document.add(new Phrase(" "+event+" ")); //document.add(jpeg); fileWriter.write("[cc] "+event+" |
"";filewriter.write("
1 | "+Calendar.getInstance().getTime()+" |
号");filewriter.write("MGXY1〔0]);++指数;}catch(ioexception documentexception e){e.printstacktrace();}}< /代码>
爪哇
1 2 3 4 5 6 7 8 9 10 11 12 | public void takeScreenshot(ITestResult result) { Calendar cal = Calendar.getInstance(); SimpleDateFormat time = new SimpleDateFormat("dd-mm-yyyy-HH-mm-ss"); String currentTime = time.format(cal.getTime()); try { File srcFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileHandler.copy(srcFile, new File("resources/screenshots/" + result.getName() +"-" + currentTime +".jpg")); } catch (IOException e) { e.printStackTrace(); } } |