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

如何在Selenium中使用TouchAction,解决W3C模式下调用报错问题

问题根因
  • 高版本ChromeDriver默认开启W3C标准模式,传统TouchActions系列接口属于非W3C规范的旧协议命令,会被直接拦截
  • Selenium 4+版本已经正式废弃TouchActions相关API,强依赖W3C标准协议,直接调用会抛出不支持命令的异常
解决方案

Python环境

方案1:快速兼容旧代码

直接放开你代码中注释的w3c关闭配置即可,不需要修改其他逻辑:

mobileEmulation = {'deviceName': 'iPhone 6'}
options = webdriver.ChromeOptions()
s = Service(r"C:\Program Files\Google\Chrome\Application\chromedriver.exe")
options.add_experimental_option('mobileEmulation', mobileEmulation)
# 放开该行注释,关闭W3C模式兼容旧TouchActions
options.add_experimental_option('w3c', False)
driver = webdriver.Chrome(options=options, service=s)

注意:该方案仅适配Chrome 110以下版本,更高版本Chrome已经强制开启W3C模式,该配置会失效

方案2:使用标准W3C动作API(推荐)

用Selenium官方推荐的ActionChains滑动接口替换旧的TouchActions操作,不需要关闭W3C模式,适配全版本Chrome:

# 替换原有的TouchActions相关代码
from selenium.webdriver.common.action_chains import ActionChains

# 原flick_element逻辑等价替换
element = driver.find_element(By.XPATH, "//div[@class='message-wrapper-indicator']/div")
ActionChains(driver)\
    .scroll_from_origin(element, 0, 200, duration=20)\
    .perform()

另外你现有代码中WebDriverWait(driver, 5).until(...)行末尾缺少闭合右括号,需要补上否则会触发语法错误

Java环境

对应两种适配方案:

  • 方案1:关闭W3C模式兼容旧代码,初始化ChromeOptions时添加配置:
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("w3c", false);
  • 方案2:使用W3C标准PointerActions替换旧TouchAction:
import org.openqa.selenium.interactions.PointerActions;
import org.openqa.selenium.interactions.PointerInput;
import java.time.Duration;

// 滑动逻辑示例
WebElement element = driver.findElement(By.xpath("//div[@class='message-wrapper-indicator']/div"));
new PointerActions(driver)
    .moveToElement(element)
    .pointerDown(PointerInput.MouseButton.LEFT.asArg())
    .moveByOffset(0, 200)
    .pointerUp(PointerInput.MouseButton.LEFT.asArg())
    .pause(Duration.ofMillis(20))
    .perform();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:36:03