使用 TouchAction
类执行滑动手势
示例代码
以下是一个完整的示例,展示了如何使用 Appium 和 TouchAction
类在 Android 设备上执行滑动手势。
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from appium.options.android import UiAutomator2Options
# 设置 Desired Capabilities
desired_caps = {
'platformName': 'Android',
'platformVersion': '11',
'deviceName': 'your_device_name', # 替换为你的设备名
'appPackage': 'com.tencent.weread',
'appActivity': '.LauncherActivity',
'unicodeKeyboard': True,
'resetKeyboard': True,
'noReset': True,
'newCommandTimeout': 6000,
'automationName': 'UiAutomator2'
}
options = UiAutomator2Options().load_capabilities(desired_caps)
# 连接 Appium Server,初始化 WebDriver
driver = webdriver.Remote('http://localhost:4723/wd/hub', options=options)
# 设置隐式等待时间
driver.implicitly_wait(10)
# 创建 TouchAction 对象
touch_action = TouchAction(driver)
# 执行滑动操作
start_x = 1048
start_y = 1408
end_x = 759
end_y = 1408
duration = 1000 # 持续时间,单位为毫秒
# 按下并滑动到目标位置
touch_action.press(x=start_x, y=start_y).wait(ms=duration).move_to(x=end_x, y=end_y).release().perform()
# 关闭会话
driver.quit()
解释
-
设置 Desired Capabilities:
- 定义了设备和应用的相关配置,包括平台、版本、设备名称、应用包名、启动活动、键盘设置、自动化引擎等。
-
初始化 WebDriver:
- 使用
webdriver.Remote
方法连接到本地的 Appium Server,并使用配置好的options
初始化 WebDriver。
- 使用
-
设置隐式等待时间:
- 使用
driver.implicitly_wait(10)
方法设置隐式等待时间为 10 秒。
- 使用
-
创建
TouchAction
对象:- 使用
TouchAction(driver)
创建一个TouchAction
对象。
- 使用
-
执行滑动操作:
- 使用
press
方法指定滑动起始坐标(start_x
,start_y
)。 - 使用
wait
方法设置滑动持续时间(ms=duration
)。 - 使用
move_to
方法指定滑动终点坐标(end_x
,end_y
)。 - 使用
release
方法释放触摸点。 - 使用
perform
方法执行滑动操作。
- 使用
-
关闭会话:
- 使用
driver.quit()
方法关闭 WebDriver 会话,释放资源。
- 使用
小结
虽然 swipe
方法在旧版本中常用,但在新的 Appium 版本中推荐使用 TouchAction
类来代替。TouchAction
类提供了更多的灵活性和控制,使得执行复杂的手势操作变得更容易和直观。