Alex Angrybambr
Alex Angrybambr

Reputation: 41

How can I get screenshot of specified element using WebDriver in C#

I have my little project written on Java and I need to rewrite it in C#.

It's almost done, but I am stuck on getting screenshot of element using Selenium webdriver. I did it in Java in the next way:

    public String saveImage(){
        String src = "";
        try{
            File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
            BufferedImage fullImg = ImageIO.read(screenshot);
            Point point = elementToScreent.getLocation();
            int eleWidth = elementToScreent.getSize().getWidth();
            int eleHeight = elementToScreent.getSize().getHeight();
            BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), eleWidth,
            eleHeight);
            ImageIO.write(eleScreenshot, "png", screenshot);
            src = path + System.currentTimeMillis() +".png";
            FileUtils.copyFile(screenshot, new File(src));
    }catch(Exception e){
        e.printstacktrace();
    }
    return src;
}

It works perfect in Java, but I have no idea how to rewrite it in C#, as I am not so familiar with it.

Could someone suggest some nice way to achieve the same in C#?

Upvotes: 2

Views: 10771

Answers (2)

Andrew
Andrew

Reputation: 11362

public Bitmap MakeElemScreenshot( IWebDriver driver, WebElement elem)
{
    Screenshot myScreenShot = ((ITakesScreenshot)driver).GetScreenshot();

    using( var screenBmp = new Bitmap(new MemoryStream(myScreenShot.AsByteArray)) )
    {
        return screenBmp.Clone(new Rectangle(elem.Location, elem.Size), screenBmp.PixelFormat);
    }
}

"using" -- is important construction as you need to dispose full screenshot image. You don't need to wait for garbage collector will be runned and your test will eat less memory.

Instead of using using construction you can use screenBmp.Dispose; manually

By the way, it's c# code. But java's code will be almost the same.

Upvotes: 3

Muhammad USman
Muhammad USman

Reputation: 208

Here i have written some code to take screenshot of an Element using c#

 FirefoxDriver driver = null;
    private WebDriverWait wait;

    // Use this function to take screenshot of an element.  

public static Bitmap GetElementScreenShot(IWebDriver driver, IWebElement element)
{
    Screenshot sc = ((ITakesScreenshot)driver).GetScreenshot();
    var img = Image.FromStream(new MemoryStream(sc.AsByteArray)) as Bitmap;
    return img.Clone(new Rectangle(element.Location, element.Size), img.PixelFormat);
}
 //testing function
    public void GetIPLocation(string IPAddress)
    {
        try
        {
            if (driver == null)
                driver = new FirefoxDriver();
            if (driver.Title != "IP Location Finder - Geolocation")
                driver.Navigate().GoToUrl("https://www.iplocation.net/");
            if (wait == null)
                wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));
            var ipTextBox = wait.Until(ExpectedConditions.ElementExists(By.CssSelector("input[type='text']")));

            ipTextBox.Clear();
            ipTextBox.SendKeys(IPAddress);
            wait.Until(ExpectedConditions.ElementExists(By.CssSelector("input[type='submit']"))).Click();

            foreach (IWebElement element in driver.FindElements(By.CssSelector("div>.col.col_12_of_12")))
            {
                if (element.FindElements(By.TagName("h4")).Count > 0)
                {                          
                     var img = GetElementScreenShot(driver, element);
                    img.Save("test.png", System.Drawing.Imaging.ImageFormat.Png);
                }
            }
        }
        catch (Exception)
        {

            throw;
        }
    }

if any issue then let me know.

Upvotes: 7

Related Questions