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

前端 未结 4 916
执笔经年
执笔经年 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:42

    The documentation would indicate that it is supported, but in practice, it does not work (at least not with the .Net bindings):

    var screenshotTaker = element as ITakesScreenshot;
    var image = screenshotTaker.GetScreenshot();
    image.SaveAsFile(fileName, ImageFormat.Jpeg); // << null exception thrown here
    

    There is a workaround that has worked for me - execute javascript on the page to get the location of the element:

    const string javascript = "return arguments[0].getBoundingClientRect()";
    var obj = (Dictionary)((IJavaScriptExecutor)_core.Driver).ExecuteScript(javascript, element);
    var rect = new Rectangle((int)double.Parse(obj["left"].ToString()),
                             (int)double.Parse(obj["top"].ToString()),
                             (int)double.Parse(obj["width"].ToString()),
                             (int)double.Parse(obj["height"].ToString()));
    

    That will give you the location of the element within the viewport, at which point you can take a screenshot of the entire page and crop it down to just the bounds of the element.

    Hopefully that helps...

提交回复
热议问题