Is it possible to capture a screen shot for a webelement directly by using WebDriver?

前端 未结 4 943
执笔经年
执笔经年 2021-01-13 07:46

At Interface TakesScreenshot page I found this:

Capture the screenshot and store it in the specified location. For WebDriver extending TakesScreens

4条回答
  •  难免孤独
    2021-01-13 08:26

    public static Bitmap FullScreen { get; set; }
    public static Bitmap Image { get; set; }
    
    public static void TakeScreenShot(ChromeDriver driver, IWebElement element)
    {
        Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot();
    
        screenshot.SaveAsFile(Environment.CurrentDirectory + @"\screens\file.bmp", ImageFormat.Bmp);
    
        FullScreen = new Bitmap(Environment.CurrentDirectory + @"\screens\file.bmp");
    
        Size element_size = element.Size;
        Point element_location = element.Location;
    
        Rectangle rect = new Rectangle(element_location, element_size);
    
        Image = FullScreen.Clone(rect, PixelFormat.Format24bppRgb);
    
        Image.Save(Environment.CurrentDirectory + @"\screens\file2.bmp", ImageFormat.Bmp);
    
    }
    
    void Main()
    {
        ChromeDriver driver = new ChromeDriver();
    
        driver.Navigate().GoToUrl("http://domain.com");
    
        Thread.Sleep(1500);
        IWebElement _element = driver.findElementById("ElementIdGoesHere");
        TakeScreenShot(driver, _element);
    }
    

    This code will take full screenshot of the page, then it will look for the _element location and the image will be saved to the disk using the rectangle size of the element.

提交回复
热议问题