This blog is going to explain how to take a screenshot of the element which is hidden under the scrollbar.
In selenium ((ITakesScreenshot)driver).GetScreenshot() takes a screenshot of the method page. Also, you can crop a specific element to capture. But when the image is hidden under the scroll bar. When you try to take a screenshot, the application will throw System.OutOfMemoryException: 'Out of memory.' error.
Let's see how to take a screenshot of the element hidden under the scrollbar.
The following is the console application code. In the code first, I have downloaded the ChromeDriver, which is the same version of the Chrome browser installed on my computer.
Then I created the instance for the driver and navigated to the URL. Then scrolled to the location where the element is to be taken. Then I took a screenshot. Calculate the page y offset and find the difference with element Y location. Then cropped the element and saved it in the local machine.
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/");
// Scroll to the element where you want to take the screenshot
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
jse.ExecuteScript("document.getElementById('screenshotDiv').scrollIntoView();");
// Take a screenshot of the page
Screenshot sc = ((ITakesScreenshot)driver).GetScreenshot();
var img = Image.FromStream(new MemoryStream(sc.AsByteArray)) as Bitmap;
// Calculate the difference between page Y offset and element Y location
var element = driver.FindElement(By.Id("screenshotDiv"));
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
var yOffset = js.ExecuteScript("return window.pageYOffset;");
var y = Convert.ToInt32(yOffset);
var diff = element.Location.Y - y;
// Crop the element to take the screenshot
var image = img.Clone(new Rectangle(element.Location.X, diff, element.Size.Width, element.Size.Height), img.PixelFormat);
// Save the image in local drive
image.Save(AppDomain.CurrentDomain.BaseDirectory + "//Screenshot.png");
}
}
}
The following image is the output of the code above. Here you can see that the pink div element was first hidden under the scroll bar. But the application scroll to the element and captures the screenshot
I hope this helps you. Keep coding.
Comments
Post a Comment