Appium:swipe被废弃,用TouchAction实现滑动手势操作

 

使用 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()

解释

  1. 设置 Desired Capabilities

    • 定义了设备和应用的相关配置,包括平台、版本、设备名称、应用包名、启动活动、键盘设置、自动化引擎等。
  2. 初始化 WebDriver

    • 使用 webdriver.Remote 方法连接到本地的 Appium Server,并使用配置好的 options 初始化 WebDriver。
  3. 设置隐式等待时间

    • 使用 driver.implicitly_wait(10) 方法设置隐式等待时间为 10 秒。
  4. 创建 TouchAction 对象

    • 使用 TouchAction(driver) 创建一个 TouchAction 对象。
  5. 执行滑动操作

    • 使用 press 方法指定滑动起始坐标(start_x, start_y)。
    • 使用 wait 方法设置滑动持续时间(ms=duration)。
    • 使用 move_to 方法指定滑动终点坐标(end_x, end_y)。
    • 使用 release 方法释放触摸点。
    • 使用 perform 方法执行滑动操作。
  6. 关闭会话

    • 使用 driver.quit() 方法关闭 WebDriver 会话,释放资源。

小结

虽然 swipe 方法在旧版本中常用,但在新的 Appium 版本中推荐使用 TouchAction 类来代替。TouchAction 类提供了更多的灵活性和控制,使得执行复杂的手势操作变得更容易和直观。

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值