在做Android应用自动化时,当出现内嵌webview页面,driver无法获取到元素信息,导致无法进行下一步,通过切换窗口的方式来进行
需要让开发人员添加一行代码:
WebView.setWebContentsDebuggingEnabled(true);
未添加时,无法获取到webview视窗
打开手机开发者选项->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] }
先下载已确定的Chromedriver版本至本地,添加到项目中 下载地址:https://registry.npmmirror.com/binary.html?path=chromedriver/
desired_caps = {}
desired_caps['showChromedriverLog'] = True
desired_caps['enableWebviewDetailsCollection'] = True
desired_caps["ensureWebviewsHavePages"] = True
desired_caps['chromedriverExecutable'] = '/xxxx/xxx/chromedriver'
获取视窗列表:
webviews = self.driver.contexts
生效的视窗:
#[NATIVE_APP] 为安卓原生、[WEBVIEW_com.xiaozhu.xzdz] 为 H5
Available contexts: ["NATIVE_APP","WEBVIEW_com.xiaozhu.xzdz"]
self.driver.switch_to.context(webviews[1])
self.driver.switch_to.context('NATIVE_APP')
下载地址:https://plus.ucweb.com/download/?spm=ucplus.11213647.0.0.22e626042F8OQp#DevTool
示例:
self.driver.find_element_by_xpath('//*[@id="app"]/div[2]/div[2]/ul/div[5]/li').click()