python+Appium自動化:各種元素定位方法


name定位

 

 

 driver.find_element_by_name('飛利浦凈水').click()

測試結果報錯:selenium.common.exceptions.InvalidSelectorException: Message: Locator Strategy 'name' is not supported for this session

一開始以為寫錯了,后面通過搜索資料才知道,name這個定位方法,appium從1.5版本后就已經拋棄了。。。

所以可以通過其他定位方式來完成。

 

classname定位

 

 

 

driver.find_element_by_class_name('android.widget.TextView').click()

這種定位方式也是有弊端的,如果當界面class元素是唯一的時候是可以用的,但是如果頁面有多個class是一樣的,這時候就可能只操作頁面元素的第一個。

 

相對定位

先找到元素的父元素節點,再通過父元素進行元素定位

root_element=driver.find_element_by_id('id')
root_element.find_element_by_class_name('android.widget.TextView').click()

 

Xpath定位

 

 

 

通過id

driver.find_element_by_xpath('//*[@resource-id="com.taobao.taobao:id/home_searchedit"]').click()

通過text

driver.find_element_by_xpath('//*[@text="XXXX"]').click()

通過class,兩種寫法

driver.find_element_by_xpath('//android.widget.TextView’).click()

driver.find_element_by_xpath('//[class="android.widget.TextView"]').click()

通過組合

driver.find_element_by_xpath('//android.widget.TextView[@text="XXXX"]’).click()

driver.find_element_by_xpath('//*[@text="XXXX" and @index="num"]').click()

 

List定位

主要使用find_elements_by_XXX來獲取一組相同class屬性的元素,然后通過數組下標來控制的定位。

 

 比如如上截圖,定位到飛利浦標簽的時候,有很多個相同的TextView,這時候可以這樣來定位,先用xpath定位到此元素,再用數據

d=driver.find_elements_by_xpath('//android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.view.View/android.support.v7.widget.RecyclerView/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.TextView')
d[0].click() #定位到飛利浦凈水

d[1].click() #定位到行李箱

 

UIautomator定位

是Android系統原生支持的定位方式,和xpath類似,且支持元素的所有屬性定位,Appium元素定位也是基於Uiautomator進行封裝的,so定位也是很強大。

使用到方法是find_element_by_android_uiautomator(),還有UiSelector()

定位搜索框為例子:

#id定位

driver.find_element_by_android_uiautomator('new UiSelector().resourceId("com.taobao.taobao:id/home_searchedit")').click()

#text定位

driver.find_element_by_android_uiautomator('new UiSelector().text("超濾凈水器 家用")').click()

#classname定位(如果有多個class元素則定位第一個)

driver.find_element_by_android_uiautomator('new UiSelector().className("android.widget.TextView")').click()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM