首页 > 解决方案 > 为 ios 设备的特定元素截屏 - safari 浏览器

问题描述

我正在尝试为 safari 浏览器上的任何特定元素截屏 - 通过 appium+webdriverio+browserStack。

appium 版本:1.15.0

这是错误日志:

Calling AppiumDriver.getElementScreenshot() with args: ["5028","e154c6f0-73b9-4306-b661-d3206aa7ba8e"] [debug] [XCUITest] Executing command 'getElementScreenshot' [debug] [RemoteDebugger] Executing atom 'getElementScreenshot' [debug] [MJSONWP (e154c6f0)] Encountered internal error running command: Error: Unable to load Atom 'getElementScreenshot' from file '/usr/local/.browserstack/appium_1.14.0_bstack/node_modules/appium-remote-debugger/atoms/getElementScreenshot.js' [debug] [MJSONWP (e154c6f0)] at getAtoms (/usr/local/.browserstack/appium_1.14.0_bstack/node_modules/appium-remote-debugger/lib/atoms.js:17:13) 2019-11-21 06:44:37:879 - [HTTP] <-- GET

请帮忙,我做错了什么吗?请提出建议,因为我想在 Safari 浏览器上通过 appium 截取特定 webElement 的屏幕截图

标签: safariwebdriverappiumwebdriver-iobrowserstack

解决方案


Afaik 目前无法仅使用 webdriverio 和 appium 截取特定 Web 元素(通过 Web 选择器)的屏幕截图。虽然 webdriverio 提供了element.saveScreenshot功能,但它似乎不适用于带有 appium 的移动设备。

我解决它的方法是截取整个页面的屏幕截图browser.saveScreenshot(filepath)(确保为此切换到本机上下文),然后使用图像库将其裁剪为元素矩形(在我的情况下是锐利的)。

我的 util 函数如下所示:

import fs from 'fs';
import path from 'path';
import sharp from 'sharp';

export function takeScreenshot(element) {
  const timestamp = moment().format('YYYYMMDD-HHmmss.SSS');
  if (fs.existsSync('reports/screenshots/')) {
    const filePath = path.join('reports/screenshots/', timestamp + '.png');
    WebView.switchToContext(CONTEXT_REF.NATIVE);
    browser.saveScreenshot(filePath);
    WebView.switchToContext(CONTEXT_REF.WEBVIEW);

    if (element) {
      const size = getRealSize(element);
      const location = getRealLocation(element);
      const outputPath = path.join('reports/screenshots/', element.selector + timestamp + '.png');
      sharp(filePath).extract({ width: size.width, height: size.height, left: location.x, top: location.y }).toFile(outputPath)
        .then(function () {
          fs.unlinkSync(filePath);
          fs.renameSync(outputPath, filePath);
        })
        .catch(function (err) {
          console.log(err);
        });
    }
  }
}

export function getPixelRatio() {
  return browser.capabilities.pixelRatio ? browser.capabilities.pixelRatio : 1;
}

export function getRealLocation(element) {
  const location = element.getLocation();
  return {
    x: Math.round(location.x * getPixelRatio()),
    y: Math.round(location.y * getPixelRatio())
  }
}

export function getRealSize(element) {
  const size = element.getSize();
  return {
    width: Math.round(size.width * getPixelRatio()),
    height: Math.round(size.height * getPixelRatio())
  }
}


推荐阅读