Appium Python 自动化测试:获取 App 元素显示名称
要通过 Appium 使用 Python 操控 App 并获取元素显示的名称,你可以使用以下步骤:
-
首先,确保你已经正确安装了 Appium 和 Python,并设置好环境变量。
-
创建一个 Python 脚本,并导入所需的库和模块:
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from appium.webdriver.common.multi_action import MultiAction
from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.common.keys import Keys
import time
- 设置 Appium 的 Desired Capabilities,包括设备类型、App 的包名和 Activity 以及 Appium Server 的地址和端口:
desired_caps = {
'deviceName': 'Android Emulator',
'platformName': 'Android',
'appPackage': 'com.example.app',
'appActivity': 'com.example.app.MainActivity',
'udid': 'emulator-5554',
'automationName': 'UiAutomator2',
'newCommandTimeout': 300
}
- 创建一个 WebDriver 实例,并连接到 Appium Server:
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
- 使用
driver.find_element_by_XXX方法找到需要获取名称的元素,并使用get_attribute('name')获取元素的显示名称:
element = driver.find_element_by_xpath('//android.widget.TextView[@text='Example']')
element_name = element.get_attribute('name')
print(element_name)
- 最后,关闭 WebDriver 实例:
driver.quit()
完整的示例代码如下所示:
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from appium.webdriver.common.multi_action import MultiAction
from appium.webdriver.common.mobileby import MobileBy
from appium.webdriver.common.keys import Keys
import time
desired_caps = {
'deviceName': 'Android Emulator',
'platformName': 'Android',
'appPackage': 'com.example.app',
'appActivity': 'com.example.app.MainActivity',
'udid': 'emulator-5554',
'automationName': 'UiAutomator2',
'newCommandTimeout': 300
}
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
element = driver.find_element_by_xpath('//android.widget.TextView[@text='Example']')
element_name = element.get_attribute('name')
print(element_name)
driver.quit()
请根据你的实际情况修改desired_caps中的设备信息、App 包名和 Activity,并确保你已经正确连接到 Appium Server。
原文地址: https://www.cveoy.top/t/topic/MI7 著作权归作者所有。请勿转载和采集!