Appium之编写H5应用测试脚本(切换到Webview)

时间:2022-02-05 12:56:00

App使用H5编写,默认方式找不到元素。启动后获取所有上下文,找到webivew_xxxx的,然后进行切换。

源码:

 package MyAppium;

 import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities; import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set; /**
* @Auther:GongXingRui
* @Date:2018/11/1
* @Description: 测试App应用(H5)
**/
public class ZBuyAppTest {
public static void main(String[] args) throws MalformedURLException, InterruptedException { DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName", "Android Sum");
capabilities.setCapability("automationName", "Appium");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("noReset", true);
// 安卓版本号,保持默认即可
// capabilities.setCapability("platformVersion", "7.0");
//启动包名,使用SDK的uiautomatorviewer查看
capabilities.setCapability("appPackage", "cn.com.shopping.halmar");
capabilities.setCapability("appActivity", "com.weshare.jiekuan.activity.LoadActivity"); AndroidDriver driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
Thread.sleep(5000); // 获取所有窗口
Set<String> contexts = driver.getContextHandles();
System.out.println("所有窗口上下文:" + contexts); // 切换窗口到WEBVIEW
driver.context("WEBVIEW_cn.com.shopping.halmar"); WebElement webElement = (WebElement) driver.findElements(By.className("_2G-P4GHfk8agQ8HDMa3Who")).get(1);
webElement.click();
Thread.sleep(3000); String result = driver.findElement(By.className("_3vza4fqJTJUBxJqQm687vB")).getText();
System.out.println("结果:" + result); driver.quit();
}
}