How to take partial screenshot (frame) with Selenium WebDriver?

后端 未结 5 1814
不思量自难忘°
不思量自难忘° 2020-12-05 01:06

Is it possible to take a screenshot with WebDriver of only one frame (not the complete window) within a frameset?

Alternatively, is it possible to define coordinate

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 01:16

    Just posting a solution based on C# on taking a specific Html element's screenshot in selenium:

    First we need to take the screen shot of entire web page using the GetScreenShot method of selenium web driver as below.

    Screenshot screenshot = ((ITakesScreenshot)this.driver).GetScreenshot(); 
    screenshot.SaveAsFile(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
    

    Then create a rectangle from the location , height and width of the specified html element. (This has to be obtained using FindElement() method of selenium by providing id or class name).

    Image img = Bitmap.FromFile(uniqueName);
    Rectangle rect = new Rectangle();
    
    if (element != null)
    {
        // Get the Width and Height of the WebElement using
        int width = element.Size.Width;
        int height = element.Size.Height;
    
        // Get the Location of WebElement in a Point.
        // This will provide X & Y co-ordinates of the WebElement
        Point p = element.Location;
    
        // Create a rectangle using Width, Height and element location
        rect = new Rectangle(p.X, p.Y, width, height);
    }
    

    Using this we are going to crop the the screenshot as below and the result will be the screenshot specific web element.

    Bitmap bmpImage = new Bitmap(img);
    var cropedImag = bmpImage.Clone(rect, bmpImage.PixelFormat);
    

    Full code as a method below:

    /// 
    /// Captures the element screen shot.
    /// 
    /// The element.
    /// Name of the unique.
    /// returns the screenshot  image 
    public Image CaptureElementScreenShot(HTMLElement element, string uniqueName)
    {
        Screenshot screenshot = ((ITakesScreenshot)this.driver).GetScreenshot();
        screenshot.SaveAsFile(filename, System.Drawing.Imaging.ImageFormat.Jpeg);
    
        Image img = Bitmap.FromFile(uniqueName);
        Rectangle rect = new Rectangle();
    
        if (element != null)
        {
            // Get the Width and Height of the WebElement using
            int width = element.Size.Width;
            int height = element.Size.Height;
    
            // Get the Location of WebElement in a Point.
            // This will provide X & Y co-ordinates of the WebElement
            Point p = element.Location;
    
            // Create a rectangle using Width, Height and element location
            rect = new Rectangle(p.X, p.Y, width, height);
        }
    
        // croping the image based on rect.
        Bitmap bmpImage = new Bitmap(img);
        var cropedImag = bmpImage.Clone(rect, bmpImage.PixelFormat);
    
        return cropedImag;
    }
    

提交回复
热议问题