Appium-webview自动化测试

一、App内webview控件的获取方法
1.Native层面
(1)uiautomator解析webview中内容并映射为原生控件,通过appium的定位方法定位控件
(2)getPageSource为DOM结构可发现webview组件和控件
缺点:虽可以通过content-desc根据文本的不同进行定位,但一旦界面中有两个控件文本内容相同,这时只能xpath定位,效率低。
2.webview层面
切换为webview上下文,切换后是正规的web,这时可以通过selenium的定位方法进行定位。
getPageSource为HTML

二、Hybird测试流程
1.先进入webview的页面
2.使用Context API寻找webview
3.使用Context 切换到Webview
4.使用CSS等web定位方式进行查找,交互
5.对webview执行完成后,使用Context重回Native层

代码表现:

#切换至webview上下文
webview = driver.contexts[1] 
driver.switch_to.context(webview)
#使用selenium方法进行定位
driver.find_element(:css,".green_button").click()
#切换回native层面
driver.switch_to.context(driver.contexts.first)

三、webview测试前提
1.低版本(API 23)的模拟器默认支持,高版本未开启webview的debug模式。使用driver.contexts只能获取到NativeAPP。
2.真机,需要代码中打开app内开关,从应用中启用webview测试(chrome浏览器打开网页默认支持调试)

四、chromedriver
appium若想和selenium一样对webview进行操作,需要借助chromedriver,才能对H5页面进行操作。
1.chromedriverExecutable:传入一个chromedriver.exe的路径即可。适用单个webview执行情况。

2.chromedriverExecutableDir:如果要测的版本有很多个webview版本,传入一个目录,目录中含有多个chromedriver版本,程序会自动去执行

五、注意问题
1.webview加载需要时间,需要等待webview界面加载出来再进行交互操作,这时可以采用显示等待。

#显示等待20s,直到指定控件展示出来,才进行一下不操作
WebDriverWait(self.driver,20).until(expected_conditions.visibility_of_element_located((By.NAME,'q')))
        self.driver.find_element_by_name("q").send_keys("自动化测试")

2.chrome浏览器虽默认支持debug调试,但需先切换到CHROMIUM才能对H5网页进行操作,用self.driver.switch_to.context(self.driver.contexts[1])进行切换.

if(Build.VERSION.SDK_INT >= bUILD.VERSION_CODES.KITKAT){
	WebView.setWebContentsDebuggingEnabled(true);
}

3.查看手机端的H5网页布局有两种方法,分别是:
(1)知道当前H5网页的网址,可以直接用chrome打开,进入开发者工具,并调至手机布局,就能看对应的标签布局。
(2)不知道当前H5网页的地址,需借助devtools,输入:chrome://inspect即可进入,连接成功后点击inspect就能进入调试工具(需要,且chrome62以上版本会出现bug,如果遇到了可以降低chrome版本)

 selenium.common.exceptions.WebDriverException: Message: An unknown server-side error occurred while processing the command. Original error: No Chromedriver found that can automate Chrome '74.0.3729'. You could also try to enable automated chromedrivers download server feature. See https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/web/chromedriver.md for more details

原因:未指定对应的chromedriver执行版本,需先下载后再选择对应版本,如下:

caps["chromedriverExecutable"] = "E:\Chromedriver\80.0.3987\chromedriver.exe"
#注意一定要加上chromedriver.exe,否则会报错,无法找到执行
caps["showChromedriverLog"] = True

你可能感兴趣的:(appium)