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

如何用Python的Selenium自动化点击#shadow-root(open)下的Cookie同意按钮?

解决Cookie授权按钮无法点击的问题

可能的问题原因及修复方案

1. Shadow Root选择器错误

你代码里用的是document.querySelector('usercentrics-roots'),但多数情况下Usercentrics的根元素是**usercentrics-root(单数)**,而非复数形式。这会导致获取的shadow root为null,但Selenium对execute_script返回的null不会立即报错,后续element.click()实际未执行任何操作。

修复:修正选择器并添加空值判断:

element = driver.execute_script("""
const root = document.querySelector('usercentrics-root');
if (!root) return null;
return root.shadowRoot.querySelector("button[data-testid='uc-accept-all-button']");
""")
if element:
    element.click()
else:
    print("未找到Cookie授权按钮")

2. 固定等待不可靠,改用显式等待

time.sleep(5)无法保证元素完全加载完成,尤其是网络环境较差时。改用WebDriverWait等待shadow root内的元素可点击:

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

driver = webdriver.Chrome()
url = "https://www.aplusa-online.com/vis/v1/en/exhprofiles/JP10FQtPTBydU4Ic9MvR7A?oid=19008&lang=2"
driver.get(url)

# 用显式等待配合JS脚本等待元素可点击
try:
    accept_button = WebDriverWait(driver, 10).until(
        lambda d: d.execute_script("""
            const root = document.querySelector('usercentrics-root');
            if (!root) return null;
            const btn = root.shadowRoot.querySelector("button[data-testid='uc-accept-all-button']");
            return btn && btn.isEnabled() ? btn : null;
        """)
    )
    accept_button.click()
    print("成功点击Accept All按钮")
except Exception as e:
    print(f"点击失败:{str(e)}")

3. 改用Selenium 4.5+原生Shadow DOM定位

如果你的Selenium版本是4.5及以上,可以直接用原生API定位shadow DOM内的元素,无需编写JS脚本:

# 先定位shadow root的宿主元素
root_host = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.TAG_NAME, "usercentrics-root"))
)
# 获取shadow root
shadow_root = root_host.shadow_root
# 在shadow root内定位可点击的按钮
accept_button = WebDriverWait(shadow_root, 10).until(
    EC.element_to_be_clickable((By.CSS_SELECTOR, "button[data-testid='uc-accept-all-button']"))
)
accept_button.click()

4. 强制JS点击(针对元素被遮挡的情况)

如果按钮被其他元素遮挡导致无法点击,可尝试用JS强制触发点击事件:

driver.execute_script("""
const root = document.querySelector('usercentrics-root');
if (root) {
    const btn = root.shadowRoot.querySelector("button[data-testid='uc-accept-all-button']");
    if (btn) btn.click();
}
""")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 14:32:51