首页 > 解决方案 > Selenium Python,我尝试关闭一个 cookie 按钮,但它结束了点击广告

问题描述

我试图关闭 whoscored.com 上的 cookie 按钮,我找到了该按钮,但是当程序点击时,它似乎点击了按钮后面的广告,它最终打开了一个新页面而不是关闭 cookie 按钮。知道我能做什么吗?

url='https://www.whoscored.com/Search/?t=Crystal+Palace'
browse=webdriver.Chrome()
browse.get(url)

time.sleep(4) 

cacheButton=browse.find_elements_by_xpath('//button')
cacheButton[1].click() #This is the "I ACCEPT" button.

这是按钮的html:

<button class="qc-cmp-button" onclick="window.__cmpui(&quot;setAndSaveAllConsent&quot;,!0)"> I accept </button>

如果有人可以帮助我,将不胜感激。

标签: pythonseleniumxpathselenium-chromedriver

解决方案


诱导WebDriverWait() 并等待element_to_be_clickable() 和后续xpath

WebDriverWait(browse,15).until(EC.element_to_be_clickable((By.XPATH,"//button[@class='qc-cmp-button' and contains(.,'I accept')]"))).click()

添加以下库。

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

代码

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

url='https://www.whoscored.com/Search/?t=Crystal+Palace'
browse=webdriver.Chrome()
browse.get(url)
WebDriverWait(browse,15).until(EC.element_to_be_clickable((By.XPATH,"//button[@class='qc-cmp-button' and contains(.,'I accept')]"))).click()

浏览器截图:

在此处输入图像描述

更新

cookie=btn=WebDriverWait(browse,15).until(EC.presence_of_element_located((By.XPATH,"//button[@class='qc-cmp-button' and contains(.,'I accept')]")))
browse.execute_script("arguments[0].click();", cookie)  

推荐阅读