ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Appium API 端点完全参考:从 W3C WebDriver 到官方插件的协议全景

Appium API 端点完全参考:从 W3C WebDriver 到官方插件的协议全景 Appium API 端点完全参考从 W3C WebDriver 到官方插件的协议全景【免费下载链接】appiumCross-platform automation framework for all kinds of apps, built on top of the W3C WebDriver protocol项目地址: https://gitcode.com/GitHub_Trending/ap/appium导读Appium 作为构建在 W3C WebDriver 协议之上的跨平台自动化框架其 HTTP 服务对外暴露了一整套 API 端点。本文以 API Endpoints 参考文档 为骨架系统梳理 Appium 主模块经 base driver 暴露的全部端点以及官方插件新增或修改的端点覆盖 WebDriver、WebDriver BiDi、JSON Wire、Mobile JSON Wire、Appium 原生扩展与其他 W3C 扩展协议。读完本文你将掌握各协议端点的用途、请求参数、响应结构、弃用状态与源码级实现原理能够准确选择合适的端点完成自动化调用并理解端点在 Appium 与底层 driver 之间如何流转。端点全景按协议分组的参考体系Appium 的 API 端点文档将所有端点按协议分组共七类各对应仓库中的一篇独立文档协议分组文档说明WebDriver Protocolwebdriver.mdW3C WebDriver 标准端点WebDriver BiDi Protocolbidi.md基于 WebSocket 的双向协议命令JSON Wire Protocoljsonwp.md遗留 JSONWP 端点大多已弃用Mobile JSON Wire Protocolmjsonwp.md遗留移动端 JSONWP 端点已弃用Appium Protocolappium.mdAppium 对 WebDriver 的扩展端点Other Protocolsothers.md其他 W3C 扩展协议CDP、WebAuthn 等Plugin Endpointsplugins.md官方插件新增或修改的端点两个关键前提需要先明确所有 Appium driver 都继承自 base driver因此天然支持 base driver 暴露的全部端点但具体 driver 可能定义自己的专属端点。需要了解特定 driver 的端点请查阅对应的 driver 文档。推荐通过 Appium 客户端库调用这些端点而不是直接用原始 HTTP 请求。客户端封装了精确的命令映射具体调用方式参见 Appium clients 文档。端点的底层流转Appium 与 driver 的分工理解端点之前先看 Appium 服务端如何处理请求这直接决定了不同协议端点的行为差异。代理机制多数 WebDriver 端点由 driver 实现protocol.ts 中driverShouldDoJwpProxy()的实现L286-L306揭示了核心机制大多数 WebDriver 端点并非在 Appium 内部实现而是被直接代理给底层 driver由 driver 负责真正的端点实现。代理触发的条件包括driver 显式声明代理处于活跃状态driver.proxyActive该命令不属于永不代理neverProxy类型请求未被proxyRouteIsAvoided的规避规则命中。实际转发发生在doWdProxy()L605-L622Appium 调用 driver 的executeCommand(proxyReqRes, req, res, sessionId)将 HTTP 请求原样转发给 driver 背后的服务器代理失败时抛出ProxyRequestError。这正是Appium 是薄调度层、driver 是实际执行者架构的体现。插件可覆盖端点请求处理流程L405-L433中还有一个关键分支若插件在命令执行链中覆盖了当前命令则didPluginOverrideProxy被置为true代理行为被跳过。这就是插件文档中Modifies the endpoint修改端点的实现基础——插件可以在不改变 URL 的前提下扩展或改写端点行为。WebDriver ProtocolW3C 标准端点W3C 端点集中在 webdriver.md与 W3C WebDriver 规范一一对应。其中值得特别注意的端点如下。createSessionAppium 的历史性改造POST /session新建 WebDriver 会话。Appium 出于历史原因实现了一个改造版本W3C 规范只接受 1 个参数而 Appium 的实现允许最多 3 个参数这是遗留 JSONWP 的要求。自 Appium 2 起 JSONWP 格式不再被支持3 个参数中的任意一个都可以用来指定 W3C capabilities。这一改造在路由源码中得到了印证W3C_ROUTES中/session的POST命令为createSession其payloadParams.optional被刻意声明为 3 个相同的capabilities见 w3c.ts源码注释明确说明这是为了保持与已弃用的多参数createSession重载的线上兼容避免对第三方插件造成破坏性变更。响应CreateResultNameDescriptionTypesessionId新会话 IDstringcapabilities经 driver 处理后的 capabilitiesobject会话生命周期与服务器状态端点方法说明响应deleteSessionDELETE /session/:sessionId关闭当前会话nullgetStatusGET /status获取 Appium 服务器当前状态GetStatusResultgetStatus的响应结构为{build, message, ready}build是包含version键的对象值对应 Appium 服务器版本message解释ready的含义ready表示服务器当前能否创建新会话。这一实现可在 appium.ts 中验证——服务器关闭时会返回ready: false与 The server is shutting down 消息正常时返回 The server is ready to accept new connections。超时与导航getTimeoutsGET /session/:sessionId/timeouts返回{command, implicit}两个超时值命令超时与隐式等待超时。timeoutsPOST /session/:sessionId/timeouts可设置implicit、pageLoad、script三个超时单位均为毫秒。源码中payloadParams.optional同时接受type、ms遗留 JSONWP 风格与script、pageLoad、implicitW3C 风格见 w3c.ts。setUrlPOST .../url导航当前顶层浏览上下文到指定 URLgetUrlGET .../url返回当前 URLback/forward/refresh分别对应历史后退、前进与刷新页面。窗口与 frame 管理端点方法说明getWindowHandle/closeWindow/setWindow/getWindowHandlesGET/DELETE/POST/GET .../window(/)获取/关闭/切换/枚举窗口句柄createNewWindowPOST .../window/new新建窗口或标签页参数type取window或tabgetWindowRect/setWindowRect/maximizeWindow/minimizeWindow/fullScreenWindow围绕.../window/rect及maximize、minimize、fullscreen获取/设置窗口尺寸位置、最大化、最小化、全屏setFrame/switchToParentFramePOST .../frame与POST .../frame/parent切换 frame / 父 frame窗口尺寸相关端点统一返回Rect对象x、y、width、height。setFrame的id参数类型为null、number或Element。元素查找与元素状态查找类端点统一接受using定位策略与value选择器两个参数端点方法搜索起点findElement/findElementsPOST .../element(s)根节点findElementFromElement/findElementsFromElementPOST .../element/:elementId/element(s)指定元素节点findElementFromShadowRoot/findElementsFromShadowRootPOST .../shadow/:shadowId/element(s)指定 shadow root 节点元素引用返回Element对象包含element-6066-11e4-a52e-4f735466cecfW3C 元素 ID与ELEMENT遗留 MJSONWP 使用的同值键shadow root 返回ShadowElement其 ID 键为shadow-6066-11e4-a52e-4f735466cecf。元素状态与属性类端点均以:elementId定位elementSelected是否选中、elementDisplayed是否可见、elementEnabled是否启用——返回布尔值getAttribute/getProperty/getCssProperty/getText/getName——返回字符串getElementRect——返回RectgetComputedRoleWAI-ARIA 角色与getComputedLabel可访问名称——无障碍测试常用click/clear/setValue发送文本参数text。脚本执行、Cookie、Actions、弹窗与截图脚本执行executePOST .../execute/sync执行同步 JS参数为script与argsexecuteAsyncPOST .../execute/async执行异步 JSscript会被追加一个完成回调参数回调的第一个实参即作为响应返回。CookiegetCookies、getCookie、setCookie、deleteCookie、deleteCookies五个端点覆盖 Cookie 的增删查。Cookie对象包含name、value、domain、expiryUnix 秒级时间戳、httpOnly、path、sameSiteLax或Strict、secure。ActionsperformActionsPOST .../actions参数actions为ActionSequence[]与releaseActionsDELETE .../actions实现 W3C 指针/按键/滚轮动作序列。弹窗postDismissAlertPOST .../alert/dismiss、postAcceptAlertPOST .../alert/accept、getAlertText、setAlertText。截图与打印getScreenshotGET .../screenshot返回 base64 编码的 PNGgetElementScreenshotGET .../element/:elementId/screenshot截取元素包围矩形区域printPagePOST .../print将页面渲染为分页 PDFbase64 编码。printPage参数较为丰富值得完整记录orientationportrait/landscape默认portrait、scale[0.1, 2]默认1、background默认false、pagePrintPageSize默认宽21.59、高27.94均须 ≥2.54/72、marginPrintPageMargins四个方向默认1须 ≥0、shrinkToFit默认true、pageRanges例如[1, 4, 8-9]。WebDriver BiDi ProtocolWebSocket 双向协议与其他基于 URL 端点的协议不同WebDriver BiDi 以WebSocket 事件形式收发命令driver 与客户端均可发送或监听。当前 Appium 支持三个命令见 bidi.md命令事件名说明bidiStatussession.status获取服务器状态响应结构复用 WebDriver 的GetStatusResultbidiSubscribesession.subscribe订阅一个或多个 BiDi 事件参数events事件名数组与可选contexts默认全局作用域[]bidiUnsubscribesession.unsubscribe退订 BiDi 事件参数同上Appium ProtocolAppium 原生扩展端点Appium Protocol 定义的是 Appium 在 W3C WebDriver 基础上的扩展端点全部集中在 appium.md是移动端自动化最常用的端点集合。会话管理getAppiumSessionsGET /appium/sessions返回所有活跃服务器会话信息id、capabilities、created毫秒级 Unix 时间戳。注意此端点必须启用session_discovery不安全特性insecure feature才能使用对应源码见 appium.ts 中的assertFeatureEnabled(SESSION_DISCOVERY_FEATURE)与 constants.ts 中的SESSION_DISCOVERY_FEATURE session_discovery常量。getAppiumSessionCapabilitiesGET /session/:sessionId/appium/capabilities返回{capabilities}对象是获取会话 capabilities 的推荐途径。会话设置与命令自省getSettings/updateSettings围绕.../appium/settings的读写端点updateSettings只更新传入的键其余设置保持不变详见 settings 指南。listCommandsGET .../appium/commands返回当前会话支持的全部 URL 端点与 BiDi 命令按来源分组Appium 基础、driver 专属、插件专属。listExtensionsGET .../appium/extensions返回当前会话支持的 execute 方法mobile:扩展命令按来源分组driver 专属、插件专属详见 execute-methods 指南。应用上下文getCurrentAppiumContextGET .../appium/context、setAppiumContextPOST .../appium/context参数name、getAppiumContextsGET .../appium/contexts——分别获取当前上下文、切换上下文、枚举全部可用上下文。这是 WebView 与原生视图切换的核心端点。事件记录与时间戳getLogEventsPOST .../appium/events返回EventHistory对象。默认只记录 driver 命令执行但 driver/插件可定义额外事件类型。响应的commands键始终存在值是由{cmd, startTime, endTime}组成的数组其他非命名空间键为 driver/插件专属事件时间戳数组命名空间键如namespace:event可由logCustomEvent添加。官方文档给出示例响应{ commands: [ { cmd: getStatus, startTime: 1756887645447, endTime: 1756887645454 } ], driverevent: [1756887645454], namespace:event: [1756887645454] }logCustomEventPOST .../appium/log_event参数vendor命名空间前缀与event事件名配合getLogEvents实现自定义事件埋点。这一能力与 event-timing 指南 呼应可用于性能分析。设备与应用管理getDeviceTimePOST .../appium/device/system_time参数format默认YYYY-MM-DDTHH:mm:ssZ返回设备系统时间。应用生命周期activateAppPOST .../activate_app、terminateAppPOST .../terminate_app、queryAppStatePOST .../app_state、installAppPOST .../install_app、removeAppPOST .../remove_app、isAppInstalledPOST .../app_installed。除installApp使用appPath应用文件的绝对路径或 URL外其余均以appId或bundleId标识应用。queryAppState返回数值状态0未安装、1未运行、2后台挂起、3后台运行、4前台运行。键盘hideKeyboardPOST .../hide_keyboard支持key、keyCode、keyName、strategy四种隐藏策略参数与isKeyboardShownGET .../is_keyboard_shown。文件传输pushFilePOST .../push_file参数data为 base64 内容、path为设备端路径、pullFilePOST .../pull_file返回 base64 文件内容、pullFolderPOST .../pull_folder返回 base64 编码的目录 zip。方向与旋转getAppiumRotation/setAppiumRotation.../rotation三维旋转x/y/z角度与getAppiumOrientation/setAppiumOrientation.../orientation取值PORTRAIT或LANDSCAPE。遗留协议端点JSON Wire 与 Mobile JSON WireJSONWP已弃用jsonwp.md 记录了遗留 JSONWP 端点多数已标记弃用并给出替代方案getSessionGET /session/:sessionIdAppium 的改造版本——若appium:eventTimingscapability 为true响应会额外包含events键。文档明确警告此端点已弃用获取 capabilities 请改用getAppiumSessionCapabilities获取事件历史请改用getLogEvents。IME 端点availableIMEEngines、getActiveIMEEngine、isIMEActivated、deactivateIMEEngine、activateIMEEngine参数engine。均标记未来将迁移到 UiAutomator2 与 Espresso driver。getOrientation/setOrientation.../orientation请改用 Appium Protocol 的getAppiumOrientation/setAppiumOrientation。getGeoLocation/setGeoLocation.../location返回{altitude, latitude, longitude}请改用 driver 专属扩展方法如mobile: getGeoLocation或mobile: getSimulatedLocation。MJSONWP已弃用mjsonwp.md 记录移动端遗留协议端点getRotation/setRotation.../rotation请改用 Appium Protocol 的旋转端点。上下文端点getCurrentContext、setContext、getContexts——请改用 Appium Protocol 的上下文三端点。网络连接getNetworkConnection/setNetworkConnection.../network_connection响应为位掩码数值ValueDataWi-FiAirplane Mode0OFFOFFOFF1OFFOFFON2OFFONOFF4ONOFFOFF6ONONOFFsetNetworkConnection的parameters形如{type: 6}。该端点已弃用请改用mobile: getConnectivity/mobile: setConnectivity等扩展方法。Other ProtocolsW3C 生态扩展端点others.md 汇集了 Appium 支持的其他协议端点覆盖 Web 平台测试的多个前沿领域Chromedriver 与 Selenium 扩展Chromedriver Protocol未正式文档化executeCdpPOST /session/:sessionId/:vendor/cdp/execute执行 Chrome DevTools Protocol 方法参数cmd方法名与params。Selenium Protocol未正式文档化getLogPOST .../se/log参数type与getLogTypesGET .../se/log/types。日志条目典型结构为{level, message, timestamp}。虚拟化 Web 平台能力Compute PressurecreateVirtualPressureSourcePOST .../pressuresource、updateVirtualPressureSourcePOST .../pressuresource/:pressureSourceTypesample取nominal/fair/serious/critical、deleteVirtualPressureSource。Generic SensorcreateVirtualSensorPOST .../sensor、getVirtualSensorInfo、updateVirtualSensorReading、deleteVirtualSensor。Device PosturesetDevicePostureposture取continuous/folded与clearDevicePosture。Web AuthenticationWebAuthn通过webauthn:virtualAuthenticatorscapability 启用包括addVirtualAuthenticator参数protocol取ctap1/u2f/ctap2/ctap2_1transport取ble/hybrid/internal/nfc/smart-card/usb以及isUserConsenting、isUserVerified、hasResidentKey、hasUserVerification、removeVirtualAuthenticator、addAuthCredential、getAuthCredential、removeAuthCredential、removeAllAuthCredentials、setUserAuthVerified。隐私与身份Global Privacy ControlsetGlobalPrivacyControl/getGlobalPrivacyControl.../privacy。PermissionssetPermissions参数descriptor与statestate取granted/denied/prompt。Federated Credential ManagementFedCM通过fedcm:accountscapability 启用包含fedCMCancelDialog、fedCMSelectAccount、fedCMClickDialogButton、fedCMGetAccounts、fedCMGetTitle、fedCMGetDialogType、fedCMSetDelayEnabled、fedCMResetCooldown八个端点。Secure Payment ConfirmationSPCsetSPCTransactionModemode取autoAccept/autoChooseToAuthAnotherWay/autoReject/autoOptOut。其他平台机制Custom HandlerssetRPHRegistrationModemode取autoAccept/autoReject/none。ReportinggenerateTestReport参数message与可选group默认default。Storage AccesssetStorageAccess参数blocked布尔值与originorigin为合法 URL 或通配符*。官方插件端点扩展与修改plugins.md 记录了官方插件对端点的贡献展示了插件机制如何在不改动协议的前提下扩展能力。Execute Driver 插件executeDriverScriptPOST /session/:sessionId/appium/execute_driver在子进程中执行 driver 脚本。参数script必填、type执行脚本的库名默认webdriverio、timeout脚本进程超时默认3600000毫秒。响应为{result, logs}。对应实现位于 execute-driver-plugin。Images 插件compareImagesPOST /session/:sessionId/appium/compare_images三种比较模式matchFeatures判断firstImage是否为secondImage的旋转/缩放/变形版本。options支持detectorNameOpenCV 特征检测器默认ORB可选AKAZE、BRISK、KAZE、MSER等、goodMatchesFactor、matchFunc描述子匹配器默认BruteForce、visualize。matchTemplate判断firstImage是否包含一个或多个secondImage实例。options支持matchNeighbourThreshold默认10、method模板匹配方法默认TM_CCOEFF_NORMED、multiple是否查找多处默认false、threshold默认0.5、visualize。getSimilarity计算两张等尺寸图片的相似度得分options支持method与visualize。三种模式的响应均为ComparisonResult其中matchTemplate与getSimilarity返回score[0.0, 1.0]相似度matchFeatures返回匹配点数量与包围矩形。修改findElement/findElements为using参数定位策略增加-image值实现按图像定位元素。修改performActions若某个 action 的origin是图像元素则移除origin并将x、y累加该图像元素的中心坐标。对应实现可参考 images-plugin 与 compare.ts。Relaxed Caps 插件修改createSession为capabilities中所有键自动添加appium:前缀除非该键已是标准 W3C capability 或已带前缀。实现见 relaxed-caps-plugin。Storage 插件所有端点可在不创建会话的情况下调用便于提前准备测试环境addStorageItemPOST /appium/storage/add参数name不含路径分隔符与sha1。响应AddRequestResult提供上传所需的两个 WebSocket 路径ws.stream流式上传、ws.events事件通知与ttlMs存活时间官方示例{ ws: { stream: /appium/storage/add/ccc963411b2621335657963322890305ebe96186/stream, events: /appium/storage/add/ccc963411b2621335657963322890305ebe96186/events }, ttlMs: 300000 }deleteStorageItemPOST /appium/storage/delete参数name返回布尔值。listStorageItemsGET /appium/storage/list返回{name, path, size}列表。resetStoragePOST /appium/storage/reset删除全部上传文件并中止未完成上传若设置APPIUM_STORAGE_KEEP_ALL环境变量则保留已上传文件见 env-vars 文档。注意版本差异1.2.0 之前端点挂载在/storage前缀下如/storage/add该旧路由仍可用但已弃用未来版本将移除。Universal XML 插件修改findElement/findElements为value选择器增加通用节点/属性名支持与getPageSource将结果中的节点/属性名翻译为通用名。实现见 universal-xml-plugin。实践建议与安全提示调用方式优先通过 Appium 客户端库 调用端点避免手工构造 HTTP 请求客户端会维护与各协议的命令映射。弃用端点迁移JSONWP/MJSONWP 端点已标记弃用新代码应使用 Appium Protocol 对应端点如getAppiumSessionCapabilities替代getSession、getAppiumContexts替代getContexts。安全性getAppiumSessions等端点依赖不安全特性insecure features开关。session_discovery允许任何人通过GET /appium/sessions获取服务器活跃会话列表仅在可信网络环境中启用详见 security 指南 与 insecure-features 参考。driver 差异base driver 端点对所有 driver 通用但 WebDriver 类端点大多被代理给底层 driver 实现见 protocol.ts 的代理逻辑实际行为、额外端点与扩展方法以具体 driver 文档为准W3C 之外的协议端点如 CDP、WebAuthn、FedCM通常只在支持对应能力的 driver/环境下生效。结语Appium 的 API 端点体系是标准协议 扩展协议 插件扩展三层架构的直观体现WebDriver 与 BiDi 提供跨平台基础能力Appium Protocol 补齐移动端专属操作Other Protocols 紧跟 W3C 生态演进插件则以端点为切入点实现能力增强。理解这套端点分层与代理/覆盖机制是高效使用 Appium 服务端 API、排查协议问题与评估插件能力的关键。全部端点细节可随时查阅 API 参考索引 下的七篇协议文档。【免费下载链接】appiumCross-platform automation framework for all kinds of apps, built on top of the W3C WebDriver protocol项目地址: https://gitcode.com/GitHub_Trending/ap/appium创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表