Android APP混合应用自动化-Appium

前言

在做Android应用自动化时,当出现内嵌webview页面,driver无法获取到元素信息,导致无法进行下一步,通过切换窗口的方式来进行


一、APP打开调试模式

需要让开发人员添加一行代码:
WebView.setWebContentsDebuggingEnabled(true);

未添加时,无法获取到webview视窗

二、增加启动参数

1、获取手机chromedriver版本号

打开手机开发者选项->WebView实现->查看具体版本号



在正式启用前,我们可以先尝试一次获取当前视窗数量:
webviews = self.driver.contexts
在日志中找到启动浏览器的版本号-"Browser": "Chrome/83.0.4103.101"

2022-05-19 06:20:04:283 - [debug] [AndroidDriver] Found 1 webview: ["WEBVIEW_com.xiaozhu.xzdz"]
2022-05-19 06:20:04:284 - [debug] [AndroidDriver] Available contexts: ["NATIVE_APP","WEBVIEW_com.xiaozhu.xzdz"]
2022-05-19 06:20:04:284 - [debug] [AndroidDriver] Connecting to chrome-backed webview context 'WEBVIEW_com.xiaozhu.xzdz'
2022-05-19 06:20:04:297 - [debug] [AndroidDriver] A port was not given, using random free port: 8001
2022-05-19 06:20:04:297 - [debug] [AndroidDriver] Passing web view details to the Chromedriver constructor: {
2022-05-19 06:20:04:297 - [debug] [AndroidDriver]   "info": {
2022-05-19 06:20:04:298 - [debug] [AndroidDriver]     "Android-Package": "com.xiaozhu.xzdz",
2022-05-19 06:20:04:298 - [debug] [AndroidDriver]     "Browser": "Chrome/83.0.4103.101",
2022-05-19 06:20:04:298 - [debug] [AndroidDriver]     "Protocol-Version": "1.3",
2022-05-19 06:20:04:298 - [debug] [AndroidDriver]     "User-Agent": "Mozilla/5.0 (Linux; Android 10; M2002J9E Build/QKQ1.191222.002; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/83.0.4103.101 Mobile Safari/537.36",
2022-05-19 06:20:04:298 - [debug] [AndroidDriver]     "V8-Version": "8.3.110.9",
2022-05-19 06:20:04:298 - [debug] [AndroidDriver]     "WebKit-Version": "537.36 (@74dd8d5ea19a92d0e6092e59a0c8bd3a40877b71)",
2022-05-19 06:20:04:298 - [debug] [AndroidDriver]     "webSocketDebuggerUrl": "ws://127.0.0.1:10900/devtools/browser"
2022-05-19 06:20:04:298 - [debug] [AndroidDriver]   }
2022-05-19 06:20:04:298 - [debug] [AndroidDriver] }
2、指定chromedriver路径

先下载已确定的Chromedriver版本至本地,添加到项目中
下载地址:https://registry.npmmirror.com/binary.html?path=chromedriver/

3、参数配置
desired_caps = {}
desired_caps['showChromedriverLog'] = True
desired_caps['enableWebviewDetailsCollection'] = True
desired_caps["ensureWebviewsHavePages"] = True
desired_caps['chromedriverExecutable'] = '/xxxx/xxx/chromedriver'

三、切换context

1、获取当前所有的视窗
获取视窗列表:
webviews = self.driver.contexts
生效的视窗:
#[NATIVE_APP] 为安卓原生、[WEBVIEW_com.xiaozhu.xzdz] 为 H5
Available contexts: ["NATIVE_APP","WEBVIEW_com.xiaozhu.xzdz"]
2、切换至webview页面

self.driver.switch_to.context(webviews[1])

3、H5 操作完之后切回 APP

self.driver.switch_to.context('NATIVE_APP')

四、在 H5 中进行元素定位和操作

1、安装调试工具

下载地址:https://plus.ucweb.com/download/?spm=ucplus.11213647.0.0.22e626042F8OQp#DevTool

根据设备找到要进行调试的webview页面,点击可调试页面列表中的[inspect]按钮,可以开启对应页面的开发者调试界面:
2、获取要操作的元素
3、selenium web操作元素

示例:

self.driver.find_element_by_xpath('//*[@id="app"]/div[2]/div[2]/ul/div[5]/li').click()

你可能感兴趣的:(Android APP混合应用自动化-Appium)