When I was using webBrowser
to automate tasks my code to save images was short and clean:
Image Getmg(WebBrowser webBrowser)
{
mshtml.HTMLWindow2 window = (mshtml.HTMLWindow2)webBrowser.Document.Window.DomWindow;
window.execScript("var ctrlRange = document.body.createControlRange();ctrlRange.add(document.getElementById('captcha-image'));ctrlRange.execCommand('Copy');", "javascript");
return Clipboard.GetImage();
}
I was just injecting javascript. Now I am using Selenium
and FireFox driver
. I've made a method to save images:
private void takeScreenshotOfElement(By elementToFind, string outputFileName) {
//find element
IWebElement my_image = driver.FindElement(elementToFind);
//scrool to element
Actions moveAction = new Actions(driver);
moveAction.MoveToElement(my_image);
moveAction.Perform();
//take screenshot of full page
ITakesScreenshot its = (ITakesScreenshot)driver;
Screenshot screenShot = its.GetScreenshot();
//convert screenShot to Bitmap
var ms = new MemoryStream(screenShot.AsByteArray);
Bitmap image = new Bitmap(Image.FromStream(ms));
//get element size
int imageWidth = my_image.Size.Width;
int imageHeight = my_image.Size.Height;
//get element position
RemoteWebElement element = (RemoteWebElement)my_image;
Point imagePosition = new Point();
imagePosition.X = element.LocationOnScreenOnceScrolledIntoView.X;
imagePosition.Y = element.LocationOnScreenOnceScrolledIntoView.Y;
//crop screenShot
Rectangle section = new Rectangle(imagePosition, new Size(imageWidth, imageHeight));
Bitmap final_image = CropImage(image, section);
//save element image
final_image.Save(outputFileName);
}
Basically it is working when elementToFing
is on the top of browser. Also I can't scroll to this element. When I see elementToFind
it is ok. But when this element is out of my view I am getting: 'System.InvalidOperationException' in WebDriver.dll
. Do you have any idea how to do it?
To be clear, this code is not working properly:
//scroll to element
Actions moveAction = new Actions(driver);
moveAction.MoveToElement(my_image);
moveAction.Perform();