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

使用Selenium测试Kith网站时,无法通过检查元素定位Cookie弹窗按钮的问题咨询

解决Kith.com Cookie授权弹窗定位与绕过问题

方案1:等待弹窗加载并通过JS执行点击

这类Cookie授权弹窗常存在动态加载或Shadow DOM的情况,直接Inspect可能无法即时定位,试试显式等待结合JS点击的方式:

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

driver = webdriver.Chrome()
driver.get("https://kith.com/")

try:
    # 最多等待10秒,直到弹窗按钮出现
    accept_btn = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CSS_SELECTOR, "button[aria-label*='Accept']"))
    )
    # 用JS执行点击,规避元素不可交互的问题
    driver.execute_script("arguments[0].click();", accept_btn)
except Exception as e:
    print(f"点击授权按钮失败: {e}")

方案2:正确设置Cookie绕过弹窗

导入Cookie失败大概率是时机或参数错误,需先绑定域名再添加正确参数的Cookie:

driver = webdriver.Chrome()
# 先打开网站,让浏览器关联目标域名
driver.get("https://kith.com/")
driver.delete_all_cookies()

# 添加同意Cookie(参数需匹配网站实际Cookie规则)
driver.add_cookie({
    "name": "cookie_consent",
    "value": "accepted",
    "domain": ".kith.com",
    "path": "/",
    "secure": True,
    "httponly": False
})

driver.refresh()

方案3:通过Chrome配置直接禁用弹窗

利用ChromeOptions设置默认允许Cookie,从根源跳过授权弹窗:

from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_experimental_option("prefs", {
    "profile.default_content_setting_values.cookies": 1,
    "profile.cookie_controls_mode": 0  # 0=允许所有Cookie,跳过授权提示
})
chrome_options.add_argument("--disable-popup-blocking")

driver = webdriver.Chrome(options=chrome_options)
driver.get("https://kith.com/")

补充:处理iframe嵌套的弹窗

若弹窗嵌套在iframe内,需先切换iframe再操作:

# 定位并切换到Cookie弹窗所在的iframe
iframe = driver.find_element(By.CSS_SELECTOR, "iframe[src*='consent']")
driver.switch_to.frame(iframe)

# 点击接受按钮
accept_btn = driver.find_element(By.CSS_SELECTOR, "button.accept")
accept_btn.click()

# 切回主页面
driver.switch_to.default_content()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:10:38