使用OpenQa在2个显示器上截图,Selenium总是引用主显示器

6ovsh4lw  于 2023-05-22  发布在  其他
关注(0)|答案(1)|浏览(98)

我试图通过调用以下(示例)代码来截取元素的屏幕截图:

var element = this.driver.FindElementByName("Example");    
var sc = element.TakeScreenshot();

现在,当我将截图与参考图像(使用OpenCvSharp)进行比较时,我一直得到非常大的错误。所以我决定看看图像,低,看,屏幕截图总是在主显示器上拍摄,应用程序(Winforms)在辅助显示器上运行。在元素上执行的所有操作都正常工作,单击它,获取它的属性,…但由于某种原因,截图不起作用。我是不是漏掉了什么,这是一个Appium问题?任何帮助将不胜感激。

eimct9ow

eimct9ow1#

当使用多个显示器时,.GetScreenshot()可能不采用元素的正确X坐标。我通过使用扩展方法根据检测到的屏幕更新X坐标并从整个屏幕的屏幕截图中取出图片来绕过这个问题。对于任何一个可能正在寻找解决方案的人来说,这是我所做的:

public static byte[] TakeSnapshot(this AppiumWebElement element, WindowsDriver<WindowsElement> driver)
    {
        Screenshot sc = driver.GetScreenshot();
        Rectangle rect = GetBoundingRectangle(element);

        using (MemoryStream ms = new(sc.AsByteArray))
        {
            using (Bitmap bmp = new(ms))
            {
                // If more than 1 screen is used, we need to adjust the rectangle's X based on screen count
                // otherwise the screenshot will be always taken on the primary screen
                int screenResolutionWidth = 1920;
                int screenCount = GetScreenCount(bmp, screenResolutionWidth);
                if (screenCount > 1)
                {
                    rect.X += (screenCount - 1) * screenResolutionWidth;
                }

                using (Bitmap elementScreenshot = bmp.Clone(rect, bmp.PixelFormat))
                using (MemoryStream croppedMemoryStream = new())
                {
                    elementScreenshot.Save(croppedMemoryStream, ImageFormat.Bmp);
                    return croppedMemoryStream.ToArray();
                }
            }
        }
    }

        private static int GetScreenCount(Bitmap bmp, int screenResWidth)
    {
        if (bmp.Width % screenResWidth != 0)
        {
            throw new ArgumentException(
                $"Invalid parameters calculating screen resolution! {nameof(bmp.Width)}={bmp.Width}, {nameof(screenResWidth)}={screenResWidth} ");
        }

        return bmp.Width / screenResWidth;
    }

相关问题