You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Appium调用TouchActions实现横幅横向滑动时报AttributeError错误如何解决

问题原因
  • 拼写错误:Appium提供的触控类名为TouchAction(单数),你代码中调用的TouchActions(末尾多了s)本身不存在
  • 调用方式错误:你已经单独导入了TouchAction类,不需要从webdriver模块下调用该类
  • 导入冲突:同时导入Selenium和Appium的TouchAction会导致类覆盖,优先保留Appium版本即可
修复步骤
  1. 修正导入语句,删除Selenium的TouchAction导入,仅保留Appium版本:
# 删除该行:from selenium.webdriver.common.touch_actions import TouchAction
from appium.webdriver.common.touch_action import TouchAction
  1. 修正触控类实例化代码,直接调用导入的TouchAction类:
# 错误写法:action = webdriver.TouchActions(driver)
action = TouchAction(driver)
补充优化建议

当前你使用绝对坐标的滑动兼容性较差,不同分辨率设备会失效,推荐基于定位到的横幅组件计算相对坐标实现滑动,示例如下:

wait = WebDriverWait(driver, 15)
element = wait.until(EC.visibility_of_element_located((By.ID, 'com.project.ProjectName:id/bannersRecyclerView')))
# 获取组件尺寸
size = element.size
# 计算起始、终止坐标:从组件右半部分滑到左半部分实现左滑
start_x = size['width'] * 0.8
start_y = size['height'] * 0.5
end_x = size['width'] * 0.2
end_y = size['height'] * 0.5
# 执行滑动
action = TouchAction(driver)
action.press(x=start_x, y=start_y).move_to(x=end_x, y=end_y).release().perform()

如果使用Appium 2.x版本,更推荐使用W3C标准的ActionChains实现触控操作:

from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.actions import interaction
from selenium.webdriver.common.actions.action_builder import ActionBuilder
from selenium.webdriver.common.actions.pointer_input import PointerInput

actions = ActionChains(driver)
actions.w3c_actions = ActionBuilder(driver, mouse=PointerInput(interaction.POINTER_TOUCH, "touch"))
actions.w3c_actions.pointer_action.move_to_location(start_x, start_y)
actions.w3c_actions.pointer_action.pointer_down()
actions.w3c_actions.pointer_action.move_to_location(end_x, end_y)
actions.w3c_actions.pointer_action.release()
actions.perform()

内容的提问来源于stack exchange,提问作者Claudaette

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 07:09:04