干货|app自动化测试之Andriod WebView如何测试
Hybrid App(混合模式移动应用)是介于 Web-app、Native-app 之间的 app,本质上是 Native-app 中嵌入 WebView 组件,在 WebView 组件里可以访问 Web App。Hybrid App 在给用户良好交互体验的同时,还具备了 Web App 的跨平台、热更新机制等优势。
Android WebView 在 Android 平台上是一个特殊的 View,用它来展示网页内容。WebView 内部实现是采用渲染引擎来展示 View 的内容,提供网页前进后退、网页放大、缩小、搜索等功能。使用 WebView 进行测试需要开发人员配合打开一个 WebView 的开关。
WebView开关
WebView 是手机应用内嵌的浏览器,在 Android 4.4 之前 WebView 内核采用的是 WebKit,Android 4.4 之后才用的是 Chrome 作为内置浏览器。它是用来加载 HTML 页面的控件。在模拟器(android6.0 版本)中是默认打开 WebView 开关的,可以直接调试和测试 WebView。真机测试时,必须在应用中打开 WebView 调试开关。要启用 WebView 调试,请在 WebView 类上调用静态方法 setWebContentsDebuggingEnabled。
webview = driver.contexts[-1]
driver.switch_to.context(webview)
WebView 案例
雪球案例,打开雪球应用,点击“交易”,点击“A 股开户”进入到开户页,验证页面正确。如下图:

def test_webview(self):
# 点击交易
self.driver.find_element(MobileBy.XPATH, '//*[@text="交易"]').click()
# 打印当前页面有哪些上下文
print(self.driver.contexts)
e = self.driver.contexts
for context in self.driver.contexts[::-1]:
if 'webview' in context.lower():
aim = context
break
# 切换上下文
self.driver.switch_to.context(aim)
# 点击'A股开户'
print(self.driver.window_handles)
A_locator = (MobileBy.XPATH, '//*[@id="Layout_app_3V4"]/div/div/ul/li[1]/div[2]/h1')
WebDriverWait(self.driver, 10).until(expected_conditions.element_to_be_clickable(A_locator))
进入到 APP 后,打开一个包含 H5 的页面,系统默认是 Native 的上下文。如果要操作 H5 上的元素,则需要切换到 WEBVIEW 的上下文。
上面的代码先通过 driver.contexts 找到所有的 contexts(即上下文),循环遍历这个contexts,找到目标的 WEBVIEW,然后切换到这个 WEBVIEW 中,再执行相应的操作。这时就可以使用 Selenium 的定位方式到 H5 页面的元素了。