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

使用Selenium爬取Transfermarkt时无法定位Cookie确认按钮

问题

我尝试用爬虫从Transfermarkt获取信息,但通过Selenium打开页面时总会出现大型Cookie确认弹窗。我尝试过复制完整XPath、相对XPath,以及使用//button[@title="ACCEPTEER ALLE"]来定位确认按钮,但始终无法找到该元素。我也使用了等待方法,但仍因找不到元素触发超时错误,而页面加载速度很快。请问问题出在哪里?

相关信息

Cookie按钮HTML代码

<button title="ACCEPTEER ALLE" class="message-component message-button no-children focusable sp_choice_type_11 last-focusable-el" style="padding: 10px 15px; margin: 5px 10px; border-width: 2px; border-color: rgb(92, 166, 255); border-radius: 4px; border-style: solid; font-size: 14px; font-weight: 400; color: rgb(255, 255, 255); font-family: verdana, geneva, sans-serif; width: 225px; background: rgb(0, 25, 63);">ACCEPTEER ALLE</button>

我的Selenium代码

league = "Primera División"
url = "https://www.transfermarkt.nl/schnellsuche/ergebnis/schnellsuche?query={}".format(league)
browser = webdriver.Chrome()
browser.get(url)
sleep(10)
    
button = browser.find_element(By.XPATH, '//button[@title="ACCEPTEER ALLE"]')
button.click()
解决方案
  • 元素处于iframe中:多数网站的Cookie弹窗会被放在独立的iframe容器内,Selenium默认只会在主文档树中查找元素,导致定位失败。解决步骤:

    1. 先定位到对应的iframe元素(可通过标签名、class或id查找)
    2. 使用browser.switch_to.frame(iframe_element)切换到该iframe
    3. 再查找并点击Cookie按钮
    4. 操作完成后用browser.switch_to.default_content()切回主文档
  • 定位表达式不够可靠:依赖title属性定位容易失效,建议改用按钮文本或更独特的class组合:

    • 文本定位XPath://button[text()="ACCEPTEER ALLE"]
    • 结合class的定位://button[contains(@class,"sp_choice_type_11") and text()="ACCEPTEER ALLE"]
  • 等待方式不合理:sleep(10)是强制等待,无法适配元素实际加载时机,改用显式等待更稳定:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 初始化浏览器并打开页面
options = webdriver.ChromeOptions()
options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36")
browser = webdriver.Chrome(options=options)
browser.get(url)

wait = WebDriverWait(browser, 15)
# 若弹窗在iframe中,先切换
# iframe = wait.until(EC.presence_of_element_located((By.TAG_NAME, "iframe")))
# browser.switch_to.frame(iframe)

# 等待按钮可点击并点击
button = wait.until(EC.element_to_be_clickable((By.XPATH, '//button[text()="ACCEPTEER ALLE"]')))
button.click()

# 切回主文档(如果切换过iframe)
# browser.switch_to.default_content()
  • 反爬机制拦截:Transfermarkt有反爬策略,需模拟真实用户环境,比如添加自定义User-Agent(如上代码所示),避免被识别为爬虫。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 21:50:40