【问题标题】:Selenium Python, i try to close a cookie button, but it ends clicking on the adSelenium Python,我尝试关闭一个 cookie 按钮,但它结束了点击广告
【发布时间】:2020-04-09 10:11:36
【问题描述】:

我试图关闭 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>

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

【问题讨论】:

    标签: python selenium xpath selenium-chromedriver


    【解决方案1】:

    诱导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)  
    

    【讨论】:

    • 我试过你的代码,但是我好像遇到了同样的问题。它只是点击后面的广告而不是 cookie 拦截器,然后打开一个新页面。您知道为什么会发生这种情况或如何解决吗?顺便说一句,我很感谢你抽出时间来帮助我。
    • @Aleksander :这不应该发生。我得到了正确的点击,点击后你可以看到快照。
    • @Aleksander :尝试使用 js 点击。让我知道这是怎么回事。我也更新了 js 点击选项。
    • 你有什么广告屏蔽之类的吗?我看到我在首页横幅旁边有广告,但你没有。
    • @Aleksander : Nope.Try js click option.check updated section?
    猜你喜欢
    • 2023-03-28
    • 2022-01-05
    • 1970-01-01
    • 2022-08-10
    • 1970-01-01
    • 2022-01-07
    • 2019-05-15
    • 2020-05-25
    • 2021-06-05
    相关资源
    最近更新 更多