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

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

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

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

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

eimct9ow

eimct9ow1#

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

  1. public static byte[] TakeSnapshot(this AppiumWebElement element, WindowsDriver<WindowsElement> driver)
  2. {
  3. Screenshot sc = driver.GetScreenshot();
  4. Rectangle rect = GetBoundingRectangle(element);
  5. using (MemoryStream ms = new(sc.AsByteArray))
  6. {
  7. using (Bitmap bmp = new(ms))
  8. {
  9. // If more than 1 screen is used, we need to adjust the rectangle's X based on screen count
  10. // otherwise the screenshot will be always taken on the primary screen
  11. int screenResolutionWidth = 1920;
  12. int screenCount = GetScreenCount(bmp, screenResolutionWidth);
  13. if (screenCount > 1)
  14. {
  15. rect.X += (screenCount - 1) * screenResolutionWidth;
  16. }
  17. using (Bitmap elementScreenshot = bmp.Clone(rect, bmp.PixelFormat))
  18. using (MemoryStream croppedMemoryStream = new())
  19. {
  20. elementScreenshot.Save(croppedMemoryStream, ImageFormat.Bmp);
  21. return croppedMemoryStream.ToArray();
  22. }
  23. }
  24. }
  25. }
  26. private static int GetScreenCount(Bitmap bmp, int screenResWidth)
  27. {
  28. if (bmp.Width % screenResWidth != 0)
  29. {
  30. throw new ArgumentException(
  31. $"Invalid parameters calculating screen resolution! {nameof(bmp.Width)}={bmp.Width}, {nameof(screenResWidth)}={screenResWidth} ");
  32. }
  33. return bmp.Width / screenResWidth;
  34. }
展开查看全部

相关问题