Search code examples
c#seleniumfindelement

Selenium C# How to FindElement of image?


Im working on a project that takes a screenshot of a product image. This image is then cropped and saved.

Here is the code

                    Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();

                    using (var ms = new MemoryStream(screenshot.AsByteArray))
                    using (var imgShot = Image.FromStream(ms))
                    using (var src = new Bitmap(imgShot))
                    {
                        IWebElement element = driver.FindElement(By.Name("viewport"));
                        Rectangle cropRect = new Rectangle(element.Location.X, element.Location.Y, element.Size.Width, element.Size.Height);

                        var clone = src.Clone(cropRect, src.PixelFormat);
                        clone.Save(_SavePath);
                    }

Referring to the image link below, How would I use C# Selenium driver.FindElement in order to select this image: This is what I'm trying to use: IWebElement element = driver.FindElement(By.Name("viewport"));

Image: http://dealer.rectron.co.za/ImageServer.aspx?QualifyingProductID=c471d4fd-fd97-48b8-a709-441b18c1830c

Here is the HTML Code of the Image:

<html><head><meta name="viewport" content="width=device-width, minimum-scale=0.1"><title>ImageServer.aspx (335×328)</title></head><body style="margin: 0px; background: #0e0e0e;">[![][1]][1]</body></html>

When I try to crop the image, I get the following exception:

System.ArgumentException: 'Rectangle '{X=0,Y=0,Width=0,Height=0}' cannot have a width or height equal to 0.'

I think that they way I'm using FindElement, might be incorrect. Thanks


Solution

  • Your locator is incorrect, you are creating a <meta> element that does not appear on the page and has no dimensions. You need to fix the locator as follows: IWebElement element = driver.FindElement(By.XPath("//img"));