java-appium-527 WebDriver协议&针对控件的操作
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
java-appium-527 WebDriver协议&针对控件的操作的更多相关文章
- WebDriver测试EXT控件(基于C#)
WebDriver测试EXT控件(基于C#)http://www.docin.com/p-748096409.html
- Aspose是一个很强大的控件,可以用来操作word,excel,ppt等文件
Aspose是一个很强大的控件,可以用来操作word,excel,ppt等文件,用这个控件来导入.导出数据非常方便.其中Aspose.Cells就是用来操作Excel的,功能有很多.我所用的是最基本的 ...
- Appium自动化(7) - 控件定位工具之Appium 的 Inspector
如果你还想从头学起Appium,可以看看这个系列的文章哦! https://www.cnblogs.com/poloyy/category/1693896.html 前言 上一篇文章介绍了另一块控件定 ...
- appium自动化测试(3)-控件定位&中文输入
参考-控件定位 http://www.2cto.com/kf/201410/340345.html appium接口 http://appium.io/slate/en/master/?python# ...
- appium ios 相对坐标点击和控件滑动操作
环境: 系统:ios 10.13.6 (17G12034) appium:1.14.0 xcode:10.1 iphone:iphone7 12.4 在尝试使用driver.tap([(a,b)],5 ...
- Selenium webdriver 之select 控件封装,解决onchange问题
使用webdriver的时候,select 控件经常会绑定onchange 事件,在selenium2.09 之前click 方法对onchange 事件有bug,2.09 以后修复了,但是根据经验也 ...
- appium通过index查找目标控件
2.1 通过判断控件属性获取控件 控件的所有属性都可以用作判断,比如它的text,index,resource-id是否clickable等,例如: 2.1.1 通过文本查找目标控件 1 2 el = ...
- java文件夹上传下载控件分享
用过浏览器的开发人员都对大文件上传与下载比较困扰,之前遇到了一个需要在JAVA.MyEclipse环境下大文件上传的问题,无奈之下自己开发了一套文件上传控件,在这里分享一下.希望能对你有所帮助. 以下 ...
- Appium自动化(6) - 控件定位工具之uiautomatorviewer 的详细介绍
如果你还想从头学起Appium,可以看看这个系列的文章哦! https://www.cnblogs.com/poloyy/category/1693896.html 前言 app定位不如web定位那么 ...
随机推荐
- struts1的parameter
1.配置文件 parameter="method" 2.请求路径 http://localhost:8081/purchaseDeclareAction.do?me ...
- python笔记01:基础知识
1.4 数字和表达式 # -*- coding:utf-8 -*- #1.4 #除法 print 1 / 2 print 1.0 / 2 print 10 / 3 print 10.0 / 3.0 p ...
- 关于RM中的X3014错误,以及mul() 、天空盒
关于 error X3014: incorrect number of arguments to numeric-type constructor 这个错误应该是某个类似float4 这样的变量初始 ...
- 关于junk jack
旨在利用一切物品打造你自己的世界.你需要砍树获得木头,挖各种矿石用火炉炼成不同东西,顺便得到不同颜色材质的石头建房子,打各种家禽获得吃的甚至烘焙.养起来繁殖,天上掉下的星星.捡到圣诞礼包中的袜子都可以 ...
- 关于Forsaken Isle
像素化的饥荒,但是和饥荒比起来,生存压力小了不少. 主要突出的是物品合成上 开始主要采集树枝,须根,岩石,燧石一个须根可以生成一根绳子 挺休闲的,种种菜,合合装备 未来版本会有魔法,潜水,巨龙,土族部 ...
- Code Sign error: Provisioning profile XXXX can't be found
[iphone]Code Sign error: Provisioning profile XXXX can't be found 如果你更新了profile,再编译iphone项目,发现下面的错误, ...
- Python mode_a
f = open("葫芦小金刚", mode="a", encoding="utf-8") # a, append 追加, 在文件的末尾写入 ...
- magento的布局文件之谜
magento的布局文件layout.xml文件详解 解析顺序 布局xml文件一般位于app/design/{area}/{package}/{theme}/layout/目录下.Layout文件一般 ...
- ReSharper2017.3的列对齐、排版格式、列对齐错误的修复
ReSharper代码排版格式 列对齐 本文提供全流程,中文翻译.Chinar坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) Chinar -- ...
- Math对象的属性和方法
Math对象是js提供给我们用于运算的方法的集合.若进行数学逻辑上不允许的运算,返回NaN. 属性:Math.E 返回算数常量e(2.718281828459045) Math.LN2 返回2的自然对 ...