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

如何使用Python Selenium修改element.style中animation-duration属性值

你之前的代码不生效是存在两处语法逻辑错误:

  1. DOM元素的style对象下没有animated子属性,CSS动画属性是直接挂载在style对象下的
  2. 带中划线的CSS属性名在JS的style对象中需要转为驼峰命名,animation-duration对应的属性名是animationDuration,或者直接使用setProperty方法设置原始CSS属性名

方案1:直接修改style对象的驼峰属性

driver.execute_script("document.getElementById('optionContainer').style.animationDuration = '.05s';")

方案2:使用setProperty方法设置(兼容性更强)

driver.execute_script("document.getElementById('optionContainer').style.setProperty('animation-duration', '.05s');")

如果执行后仍不生效,可以尝试以下优化方案:

优化1:先等待元素加载完成再修改

避免元素还未渲染完成就执行JS导致失效:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 最多等待10秒直到元素出现
target_ele = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.ID, 'optionContainer'))
)
# 把元素作为参数传入JS执行,避免二次查找偏差
driver.execute_script("arguments[0].style.animationDuration = '.05s';", target_ele)

优化2:带!important优先级覆盖

如果原属性是通过CSS类设置了!important规则,直接修改style优先级不够,可以强制加优先级:

driver.execute_script("document.getElementById('optionContainer').style.setProperty('animation-duration', '.05s', 'important');")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 20:57:03