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

如何用Python Selenium批量替换页面所有#e7e7e7色值为#318c89

解决方案

以下两种方案都可以通过Selenium执行JS实现全页色值替换,可根据你的实际场景选择:

方案1:批量替换内联样式色值

适用于色值全部写在元素style属性内的场景,就是你给出的示例代码的场景:

from selenium import webdriver

# 初始化浏览器,可根据你的实际使用替换为Firefox/Edge等
driver = webdriver.Chrome()
driver.get("替换为你的目标页面地址")

# 执行JS完成替换
driver.execute_script("""
document.querySelectorAll('*[style]').forEach(el => {
    // gi修饰符可忽略大小写匹配,#E7E7E7也会被替换
    el.style.cssText = el.style.cssText.replace(/#e7e7e7/gi, '#318c89');
});
""")

方案2:全量覆盖样式(适配范围更广、性能更高)

如果色值还存在于页面内嵌的<style>样式规则中,可使用该方案,内联+样式表规则都能覆盖:

driver.execute_script("""
// 处理样式表内的规则
Array.from(document.styleSheets).forEach(sheet => {
    try {
        Array.from(sheet.cssRules || sheet.rules).forEach(rule => {
            if (!rule.style) return
            for (let i = 0; i < rule.style.length; i++) {
                const prop = rule.style[i]
                const val = rule.style.getPropertyValue(prop).toLowerCase()
                if (val === '#e7e7e7' || val === 'rgb(231, 231, 231)') {
                    rule.style.setProperty(prop, '#318c89', rule.style.getPropertyPriority(prop))
                }
            }
        })
    } catch (err) {
        // 跨域引入的外部样式表会报权限错误,直接跳过即可
    }
})
// 兼容处理内联样式
document.querySelectorAll('*[style]').forEach(el => {
    el.style.cssText = el.style.cssText.replace(/#e7e7e7/gi, '#318c89')
})
""")

注意事项

  • 如果页面有动态加载的内容,需要等内容渲染完成后再执行上述代码,或者每次动态内容加载完成后重新执行一次
  • 如果需要替换的色值还有其他格式(比如rgba、hsl),补充对应的匹配判断条件即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 20:24:03