AppiumDriver的各種findElement方法的嘗試,嘗試的目標應用是SDK自帶的Notepad應用。
1. findElementByName
1.1 演示樣例
el = driver.findElementByName("Add note"); assertThat(el.getText(),equalTo("Add note"));
1.2 怎樣獲得Name
安卓設備沒有找到適合的方法,嘗試用Appium Inspector,可是使用了當前最新的“AppiumForWindows-1.2.3.1”沒有看到這個屬性,且Inspector在Windows以下非常的不穩定,非常easycrash。真心期望Appium團隊盡快解決問題
iOS設備倒能夠用Appium Inspector獲得(下面圖片來自網上)
1.3 建議
個人建議能夠嘗試先用view顯示的文本作為name看能否拿到該控件,依照我個人的經驗一般都是會成功的。所以我非常懷疑安卓上面控件的name是否就等於text。
假設確實還是不行的話就僅僅好放棄用name了。
或者等待Appium后來的穩定的inspector公布后看能否夠獲得控件的name。
這種方法在Appium1.0之后事實上已經過時而要被findElementByAccessibilityId代替得了。不知道為什么還能調用,猜想是Appium團隊想保留一定的兼容性以平滑過度吧。請查看:https://github.com/appium/appium/blob/master/docs/en/advanced-concepts/migrating-to-1-0.md
2. findElementByAndroidUIAutomator
2.1 演示樣例
el = driver.findElementByAndroidUIAutomator("new UiSelector().text(\"Add note\")"); assertThat(el.getText(),equalTo("Add note"));
2.2 怎樣獲得UIAutomator參數
UIAutomator獲取控件的方式多種多樣,都是通過UiSelector對象來去查找,比方使用view的text文本去當前窗體查找控件,這里不做累述,往后會另起一篇文章來描寫敘述UIAUtomator獲取控件的方式,到時直接套用進來就能夠了。
3. findElementByClassName
3.1 演示樣例
el = driver.findElementByClassName("android.widget.TextView"); assertThat(el.getText(),equalTo("Add note"));
3.2 怎樣獲得控件的ClassName
能夠使用UIAutomatorViewer工具直接查看
3.3 建議
使用ClassName一般獲得的view都不止一個,所以應該須要遍歷一遍得到的views,然后縮寫搜索條件來獲得目標控件。演示樣例中由於僅僅有一個textview控件在窗體上面,所以不須要遍歷。
4. findElementById
4.1 演示樣例
el = driver.findElementById("android:id/title"); assertThat(el.getText(),equalTo("Add note"));
4.2 怎樣獲得Resource Id
能夠通過UIAutomatorViewer獲得
4.3 建議
假設目標設備的API Level低於18則UIAutomatorViewer不能獲得相應的Resource ID,僅僅有等於大於18的時候才干使用。5. findElementByAccessibilityId
5.1 演示樣例
el = driver.findElementByAccessibilityId("menu_add_note_description"); assertThat(el.getText(),equalTo("node"));
5.2 怎樣獲得AccessibilityId
5.3 凝視
TextView控件TalkBack能夠直接讀出里面的內容,可是ImageView TalkBack就僅僅能去讀contentDescription的值,告訴用戶這個圖片究竟是什么。
6. findElementByCssSelector
7. findElementByLinkText
8. findElementByPartialLinkText
9.findElementByTagName
10.findEelementByXPath
10.1 演示樣例
el = driver.findElementByXPath("//android.widget.TextView[contains(@text,'Add note')]"); //el = driver.findElement(By.xpath("//android.widget.TextView")); assertThat(el.getText(),equalTo("Add note"));
10.2 XPath格式變化
從老版本號的Appium0.18.x升級到如今的Appium1.x后,注意class name和xpath策略的變化:你如今須要使用FQCN來描寫敘述你的控件。也就是說原來的:
findElementByXpath(""//TextView[contains(@text,'Add note')]"")
須要改成
findElementByXpath("//android.widget.TextView[contains(@text,'Add note')]")
具體變動請查看《Appium0.18.x遷移到Appium1.x須知事項》
10.3參考
11. 終極方法:AppiumDriver getPageSource

sometimes uiautomator fails to create the dump.xml. A client side retry may help. I don't think there's much we can do about the problem until Google fixes uiautomator.