1.获取handle,方式如下
Set contexts = driver.getContextHandles();
for (Object context : contexts) {
System.out.println((String) context);
}
控制台会输出以下信息,一般webview命名方式都为WEBVIEW_开头,后面是包名
NATIVE_APP
WEBVIEW_com.xxx.xxx.xxx
2.在第一步已经获取handle,通过以下方法可以切换到webview页面
/**
* 在webview与native切换handle
* @param handle 切换NATIVE和WEBVIEW
*/
public void switchToWebview(String handle){
Set contexts = driver.getContextHandles();
try {
for (Object context : contexts) {
System.out.println((String) context);
if (handle.contains((String) context)){
driver.context(handle);
}
}
logger.info("切换到了: " + handle + "\n");
}catch (NoSuchContextException e){
logger.error("没有这个context:" + handle, e + "\n");
Assert.fail("没有这个context:" + handle, e);
}
实际结果如下:
NATIVE_APP
WEBVIEW_com.xxx.xxx
[INFO ] 2019-05-22 12:36:59,015 method:com.xxx.xxx.common.AppiumApi.changeToWebview(AppiumCommonApi.java:69)
切换到了: WEBVIEW_com.xxx.xxx
[INFO ] 2019-05-22 12:36:59,016 method:com.xxx.xxx.controller.Text.click(Text.java:44)
点击操作
[INFO ] 2019-05-22 12:36:59,016 method:com.xxx.xxx.controller.AbstractControl.getValidElement(AbstractControl.java:242)
查找元素[xxx:【确认】] → 定位方式[By.xpath: /html/body/div[66]/span/div/div/div[3]/div[2]]
[INFO ] 2019-05-22 12:36:59,643 method:com.xxx.xxx.controller.Text.click(Text.java:44)
点击操作
3.chrome版本需要保持一致,如果不一致可能会导致报错,信息在appium日志中有体现,解决方法是升级客户端chromedriver或者下载对应的chromedriver,版本与下载地址:Chromedriver/Chrome compatibility。如果下载的 是对应的,需要更改mac下的默认chromedriver,或者,启动appium时指定
appium --chromedriver-executable /Users/mc/software/chrome/2.34/chromedriver
我的路径如下:
MC:_appium-chromedriver@4.7.0@appium-chromedriver Smarter$ pwd
/usr/local/lib/node_modules/appium/node_modules/_appium-chromedriver@4.7.0@appium-chromedriver
4.除了版本还需要配置
capabilities.SetCapability("browserName", "Chrome");
ChromeOptions options = new ChromeOptions();
options.AddAdditionalCapability("androidProcess", "com.xxx");
capabilities.SetCapability(ChromeOptions.Capability, options);