1.WebDriver协议
https://www.w3.org/TR/webdriver/#list-of-endpoints
1.1查看当前所有的session情况
http://127.0.0.1:4723/wd/hub/sessions
<img src="https://img2018.cnblogs.com/blog/1418970/201810/1418970-20181005113050038-1374996098.png" width="500"
1.2查看指定session
http://127.0.0.1:4723/wd/hub/session/${sessionId}
1.3获取source
http://127.0.0.1:4723/wd/hub/session/${sessionId}/source
2.针对控件进行操作
- click()
- sendKeys()
- clear() 清空
- findElement() 二次定位,用的少
- getAtttibute() 获取属性
- getLocation()获取X Y
- 是否展示isDisplayed()
public class XueqiuDemo {
private AndroidDriver driver;
@Before
public void setUp() throws MalformedURLException {
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.setCapability("platformName", "android");
desiredCapabilities.setCapability("deviceName", "domo");
desiredCapabilities.setCapability("appPackage", "com.xueqiu.android");
desiredCapabilities.setCapability("appActivity", ".view.WelcomeActivityAlias");
URL remoteUrl = new URL("http://localhost:4723/wd/hub");
driver = new AndroidDriver(remoteUrl, desiredCapabilities);
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
}
@Test
public void sampleTest() throws InterruptedException {
exist_do("//*[@text=\"允许\"]").click();
Thread.sleep(2000);
locate("com.xueqiu.android:id/user_profile_icon").click();
Thread.sleep(2000);
locate("com.xueqiu.android:id/tv_login").click();
Thread.sleep(2000);
locate("com.xueqiu.android:id/tv_login_by_phone_or_others").click();
Thread.sleep(2000);
System.out.println("获取某个属性getAttribute:"+locate("com.xueqiu.android:id/register_phone_number").getAttribute("text"));
System.out.println("获取坐标getLocation():"+locate("com.xueqiu.android:id/register_phone_number").getLocation());
System.out.println("获取相对位置getRect():"+locate("com.xueqiu.android:id/register_phone_number").getRect());
System.out.println("获取长度和高度getSize():"+locate("com.xueqiu.android:id/register_phone_number").getSize());
System.out.println("获取控件的className getTagName():"+locate("com.xueqiu.android:id/register_phone_number").getTagName());
System.out.println("获取text属性getText()"+locate("com.xueqiu.android:id/register_phone_number").getText());
System.out.println("是否展示isDisplayed()"+locate("com.xueqiu.android:id/register_phone_number").isDisplayed());
System.out.println("toString():"+locate("com.xueqiu.android:id/register_phone_number").toString());
System.out.println("是否可用isEnabled():"+locate("com.xueqiu.android:id/register_phone_number").isEnabled());
System.out.println("是否选中isSelected():"+locate("com.xueqiu.android:id/register_phone_number").isSelected());
System.out.println("hashCode():"+locate("com.xueqiu.android:id/register_phone_number").hashCode());
System.out.println("getClass()"+locate("com.xueqiu.android:id/register_phone_number").getClass());
//System.out.println(""+locate("com.xueqiu.android:id/register_phone_number").);
locate("com.xueqiu.android:id/register_phone_number").sendKeys("123456789");
//寻找子元素
locate("//android.widget.LinearLayout[@resource-id=\"com.xueqiu.android:id/register_module\"]").findElement(By.id("com.xueqiu.android:id/register_phone_number")).clear();
driver.pressKeyCode(4);
}
public WebElement exist_do(String el){
if (locate(el).isDisplayed()){
return locate(el);
}
else{
return null;
}
}
public WebElement locate(String locate){
if (locate.matches("\\/\\/.*")){
return driver.findElementByXPath(locate);
}else{
return driver.findElementById(locate);
}
}
@After
public void tearDown() {
driver.quit();
}
}
执行结果:
objc[16328]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/bin/java (0x10bdb24c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x10ddf14e0). One of the two will be used. Which one is undefined.
十月 04, 2018 6:33:49 下午 io.appium.java_client.remote.AppiumCommandExecutor$1 lambda$0
信息: Detected dialect: W3C
获取某个属性getAttribute:请输入手机号
获取坐标getLocation():返回左上方的坐标(198, 655)
获取相对位置getRect():org.openqa.selenium.Rectangle@d0006a20
getRect().width,getRect().height,返回区域大小,同getRect()
getRect().x,getRect().y,返回左上角的坐标,同getLocation()
获取长度和高度getSize():(849, 121)
获取控件的className getTagName():android.widget.EditText
获取text属性getText()请输入手机号
是否展示isDisplayed()true
toString():[[io.appium.java_client.android.AndroidDriver, Capabilities: {appActivity=.view.WelcomeActivityAlias, appPackage=com.xueqiu.android, databaseEnabled=false, desired={platformName=android, appActivity=.view.WelcomeActivityAlias, appPackage=com.xueqiu.android, deviceName=domo}, deviceManufacturer=Xiaomi, deviceModel=Redmi Note 5, deviceName=406e8f3, deviceScreenSize=1080x2160, deviceUDID=406e8f3, javascriptEnabled=true, locationContextEnabled=false, networkConnectionEnabled=true, platform=LINUX, platformName=Android, platformVersion=8.1.0, takesScreenshot=true, warnings={}, webStorageEnabled=false}] -> id: com.xueqiu.android:id/register_phone_number]
是否可用isEnabled():true
是否选中isSelected():false
hashCode():1573
getClass()class io.appium.java_client.android.AndroidElement
Process finished with exit code 0
3.针对driver进行操作
- driver.getPageSource(); 可用,获取页面的source
- driver.getCapabilities(); 可用,获取capabilities
- driver.navigate().back(); 可用,后退同back
- driver.navigate().forward(); 怎么用?应用中前进失败,浏览器前进失败
- driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS); 可用
- driver.getKeyboard().sendKeys().releaseKey().pressKey() 怎么用?字符串传入失败
- driver.rotate();切换屏幕方向
- driver.rotate(ScreenOrientation.LANDSCAPE); 横屏
- driver.rotate(ScreenOrientation.PORTRAIT);竖屏
- driver.execute();怎么用?传入命令失败
- driver.getAutomationName(); 如果capabilities没有传入automationName,输出null
- driver.getCurrentUrl();怎么用?方法未实现
- driver.getDeviceTime();Fri Oct 5 16:38:26 CST 2018
- driver.getPlatformName();android
- driver.hideKeyboard();可用
- driver.lockDevice(); 锁屏可用
- driver.runAppInBackground();怎么用?
- driver.openNotifications();打开通知栏
- driver.startActivity(ac);怎么用?页面没有启动
#java
Activity ac = new Activity("com.xueqiu.android",".view.WelcomeActivityAlias");
driver.startActivity(ac);
- shake 没有找到这个命令
- driver.getCurrentPackage();可用,返回当前包名
- driver.currentActivity();可用,返回当前页面
4.针对app操作
- driver.installApp("/Users/title.apk");可用
- driver.removeApp(bundleId);iOS专用,未验证
- driver.isAppInstalled(bundleId);iOS专用,未验证
- driver.closeApp();可用,停止应用
- driver.launchApp();可用,注意:启动过程需要时间等待。
public void TestDriver() throws InterruptedException{
exist_do("//*[@text=\"允许\"]").click();
Thread.sleep(8000);
System.out.println("close app");
driver.closeApp();
day_time();
Thread.sleep(10000);
System.out.println("launch app");
driver.launchApp();
day_time();
Thread.sleep(8000);
exist_do("//*[@text=\"允许\"]").click();
}
public void day_time(){
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(df.format(date));
}
- driver.resetApp(); 重置应用
- driver.getAppStringMap()怎么用
- driver.getContextHandles();[NATIVE_APP]
- driver.getContext().toString();NATIVE_APP
- driver.context("NATIVE_APP");io.appium.java_client.android.AndroidDriver, Capabilities: {appActivity=.view.WelcomeActivityAlias, appPackage=com.xueqiu.android, automationName=UiAutomator2, databaseEnabled=false, desired={platformName=android, appActivity=.view.WelcomeActivityAlias, appPackage=com.xueqiu.android, automationName=UiAutomator2, deviceName=domo, newCommandTimeout=1200, noReset=true}, deviceApiLevel=27, deviceManufacturer=Xiaomi, deviceModel=Redmi Note 5, deviceName=406e8f3, deviceScreenDensity=440, deviceScreenSize=1080x2160, deviceUDID=406e8f3, javascriptEnabled=true, locationContextEnabled=false, networkConnectionEnabled=true, newCommandTimeout=1200, noReset=true, pixelRatio=2.75, platform=LINUX, platformName=Android, platformVersion=8.1.0, statBarHeight=66, takesScreenshot=true, viewportRect={left=0, top=66, width=1080, height=1964}, warnings={}, webStorageEnabled=false}
5.手势操作
- press 按
- release 释放
- moveTo 滑动
- tap wait
** tap与click的区别:tap是针对屏幕的点击,传入的是坐标PointOption,click针对的是元素
根据web driver协议,click需要传入element id,tap不需要 - longPress 长按
- cancel 取消
- perform 执行
- scroll 滚动执行失败
注意:按照官方示例,代码提示参数错误。
// 示例代码https://github.com/appium/appium/blob/master/docs/en/commands/interactions/touch/scroll.md
TouchActions action = new TouchActions(driver);
action.scroll(element, 10, 100);
action.perform();
API传参发生改变,注意参数类型,press只支持PointOption.point(x坐标,y坐标)此处为绝对坐标,
//官方示例
@Test
public void horizontalSwipingTest() throws Exception {
login();
driver.findElementByAccessibilityId("slider1").click();
MobileElement slider = driver.findElementByAccessibilityId("slider");
Dimension size = slider.getSize();
TouchAction swipe = new TouchAction(driver).press(slider, 0, size.height / 2).waitAction(2000)
.moveTo(slider, size.width / 2, size.height / 2).release();
swipe.perform();
}
结合示例,页面滑动代码
public void TestDriver() throws InterruptedException{
Thread.sleep(8000);
//获取控件列表,并迭代打印text
List<WebElement> con = driver.findElementsById("com.xueqiu.android:id/topic_text");
for(WebElement sub:con){
System.out.println(sub.getText());
Thread.sleep(3000);
}
TouchAction act = new TouchAction(driver).press(PointOption.point(con.get(1).getLocation().x,con.get(1).getLocation().y)).moveTo(PointOption.point(con.get(1).getLocation().x,500)).perform();
swipeToUp(driver);
Thread.sleep(5000);
}
可以在SwipeClass.java中,写入滑动的方法
public class SwipeClass {
static Duration duration=Duration.ofSeconds(1);
public void swipeToUp(AndroidDriver driver){
int width = driver.manage().window().getSize().width;
int height = driver.manage().window().getSize().height;
TouchAction act = new TouchAction(driver).press(PointOption.point(width/2,height*3/4)).waitAction(WaitOptions.waitOptions(duration)).moveTo(PointOption.point(width/2,height/4)).release();
act.perform();
}
public void swipeToDown(AndroidDriver driver){
int width = driver.manage().window().getSize().width;
int height = driver.manage().window().getSize().height;
TouchAction act = new TouchAction(driver).press(PointOption.point(width/2,height*1/4)).waitAction(WaitOptions.waitOptions(duration)).moveTo(PointOption.point(width/2,height*3/4)).release();
act.perform();
}
public void swipeToLeft(AndroidDriver driver){
int width = driver.manage().window().getSize().width;
int height = driver.manage().window().getSize().height;
TouchAction act = new TouchAction(driver).press(PointOption.point(width*3/4,height/2)).waitAction(WaitOptions.waitOptions(duration)).moveTo(PointOption.point(width/4,height/2)).release();
act.perform();
}
public void swipeToRight(AndroidDriver driver){
int width = driver.manage().window().getSize().width;
int height = driver.manage().window().getSize().height;
TouchAction act = new TouchAction(driver).press(PointOption.point(width/4,height/2)).waitAction(WaitOptions.waitOptions(duration)).moveTo(PointOption.point(width*3/4,height/2)).release();
act.perform();
}
}
//直接引用即可
@Test
public void TestDriver() throws InterruptedException{
Thread.sleep(8000);
swipe.swipeToUp(driver);
Thread.sleep(1000);
swipe.swipeToLeft(driver);
Thread.sleep(1000);
swipe.swipeToRight(driver);
Thread.sleep(1000);
swipe.swipeToDown(driver);
Thread.sleep(1000);
}
FAQ
1.遇到不会的方法,去查看appium示例
https://github.com/appium/appium/tree/master/docs/en 有些API已经变更,不一定能用
https://github.com/appium-boneyard/sample-code GitHub可能搜索不到sample-code