Appium自动化(4) - 定位

# 可定位的控件属性

App中的属性 等价 Web 中的属性 代码表达式 注意点
resource-id id driver.find_element_by_id("id")
driver.findElement(By.id("id"))
在App中,id可能不是唯一的
class class/tag driver.find_element_by_class_name("class")
driver.findElement(By.className("class"))
xpath:
//class[id = "id"]
1、当使用 class_name 去定位时,可以理解成类名
2、当使用xpath定位时,class就是tag(标签名),并不是类名。
text name driver.find_element_by_name("name")
driver.findElement(By.name("name"))
name是一个属性 (appium)开始废弃了该方法
content-desc driver.find_element_by_accessibility_id("desc") content-desc属性是用来描述该元素的作用的

定位入门

软件:微博国际版

import time
from appium import webdriver

desired_caps = {
  "platformName": "android",
  "deviceName": "bc3ef5d5",
  "appPackage": "com.weico.international",
  "appActivity": ".activity.MainFragmentActivity",
  "noReset": True,
  "newCommandTimeout": 6000
}

driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps)
test = driver.find_element_by_class_name("android.widget.TextView")
print(test)
print("打印1:" + test.text)

test = driver.find_element_by_xpath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/androidx.drawerlayout.widget.DrawerLayout/android.view.ViewGroup/android.widget.RelativeLayout/android.widget.TabHost/android.widget.FrameLayout/android.view.ViewGroup/android.widget.FrameLayout/android.widget.FrameLayout/androidx.recyclerview.widget.RecyclerView/android.widget.LinearLayout[2]/android.widget.RelativeLayout[1]/android.widget.TextView[1]")
print("打印2:" + test.text)

test = driver.find_element_by_xpath("//*[contains(@text,'冈瓦纳')]")
print("打印3:" + test.text)


>>>
打印1:查看新微博
打印2:冈瓦纳
打印3:冈瓦纳

为什么打印1是,查看新微博?

因为多个class_name的名字是一样的,find_element_by只返回第一个。如果要全部返回,则改成find_elements_by匹配多个元素,再更具索引去匹配

driver = webdriver.Remote("http://localhost:4723/wd/hub", desired_caps)
test = driver.find_elements_by_class_name("android.widget.TextView")
for i in test:
    print("打印1:" + i.text)
    
>>>
打印1:查看新微博
打印1:全部
打印1:
打印1:烫师傅
打印1:11 分钟前
打印1:iQOO 3 5G性能旗舰
...
posted @ 2021-07-18 01:17  dongye95  阅读(56)  评论(0编辑  收藏  举报