Tuesday, March 21, 2017

Selenium WebDriver – Taking screenshot for a specific element (C#)

This code will demonstrate how to take a screenshot of a specific element while ignoring the rest of the browser elements.

תוצאת תמונה עבור ‪selenium webdriver screenshot‬‏

Code:
[TestMethod]
public void PrinSpecificElement ()
{
IWebElement ElementToCapture;
IWebDriver FirefoxInstance = new FirefoxDriver ();
FirefoxInstance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(60));
FirefoxInstance.Navigate().GoToUrl("http://www.machtested.com");
FirefoxInstance.Manage().Window.Maximize();

//Select a specific element from my Blog (The Main Title in this case)
ElementToCapture = FirefoxInstance.FindElement(By.ClassName("titlewrapper"));

//Get the element Size
int The_Element_Width = ElementToCapture.Size.Width;
int The_Element_Height = ElementToCapture.Size.Height;

//Get the Element location Via X/Y coordinates
int The_Element_Location_X = ElementToCapture.Location.X;
int The_Element_Location_Y = ElementToCapture.Location.Y;

//Creating the Rectangle that we going to use to extract the element
Rectangle Test = new Rectangle (The_Element_Location_X, The_Element_Location_Y, The_Element_Width, The_Element_Height);

//Take Screenshot and save it on TMP file
((ITakesScreenshot)FirefoxInstance).GetScreenshot().SaveAsFile(@"c:\TMP.jpeg", ImageFormat.Jpeg);

//import The File that we save earlier
Bitmap ImportFile = new Bitmap(@"c:\TMP.jpeg");

//Clone and extract the requested Element (Based on our Rectangle)
Bitmap CloneFile = (Bitmap)ImportFile.Clone(Test, ImportFile.PixelFormat);

//Save The Extract Element
CloneFile.Save(@"c:\SpecificElementAfter.jpeg");

//Dispose the TMP file that we don't need anymore
ImportFile.Dispose();

//Delete the TMP file
File.Delete(@"c:\TMP.jpeg");

}

1 comment:

  1. Nice Feature...
    FYI: For Java Version of code, refer below link.
    http://advancedtestautomation.blogspot.in/2016/07/capture-screenshot-of-required-element.html

    ReplyDelete

My Presentations