How to Take a Screenshot of a Particular Element in Selenium with C# .NET
This blog is going to explain how to take a screenshot of a particular element using selenium through C # .NET
The following is a C# console application code.
1. ChromeDriver, the same version of the Chrome browser, was first downloaded.
2. The instance has been created and navigated to the webpage.
3. The element to be captured is found using the FindElement() method.
4. The screenshot was taken using the GetScreenshot() method.
5. The image taken is cropped using the Clone() method.
6. The finally cropped image is stored in the specified path.
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System;
using System.Drawing;
using System.IO;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
using WebDriverManager.Helpers;
namespace SampleConsoleApp
{
class Program
{
static void Main(string[] args)
{
// Download the same version of chromedriver
var chromeDriverPath = new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser);
// Get a path of chromedriver
string chromeDirectoryPath = System.IO.Path.GetDirectoryName(chromeDriverPath);
// Create instance by passing the path of the chromedriver directory
IWebDriver driver = new ChromeDriver(chromeDirectoryPath);
// Navigate to URL
driver.Navigate().GoToUrl("https://localhost:44311/");
// Find the element where the screenshot should be taken
var element = driver.FindElement(By.Id("contentDiv"));
//Take the screenshot
Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
var img = (Bitmap)Image.FromStream(new MemoryStream(screenshot.AsByteArray));
// Crop the element to be captured
var image = img.Clone(new Rectangle(element.Location, element.Size), img.PixelFormat);
//Save the screenshot
image.Save(AppDomain.CurrentDomain.BaseDirectory + "//Screenshot.png");
}
}
}
The output of the code above is below. The blue div container is captured here.
I hope this helps you. Keep coding.
Comments
Post a Comment