无法点击并在python Selenium中弹出“接受Cookie”

7dl7o3gd  于 2023-01-20  发布在  Python
关注(0)|答案(2)|浏览(130)

我试着从一个网站上搜集一些价格信息,并找到不同州和城市的不同价格。然而,一个"接受Cookie"弹出窗口出现了,我需要单击它,我的代码才能成功,但我很难让Selenium找到任何可以单击的东西
这里是网站www.example.comwww.kettlebellkings.com
下面是按钮的html:

<button role="button" data-testid="uc-accept-all-button" class="sc-eDvSVe hSwgIR" style="margin: 0px 6px;">Accept All</button>

我一直在使用Expected conditions,但每次都超时。下面是我的代码:

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

path = "C:\Program Files (x86)\msedgedriver.exe"
driver = webdriver.Edge('www.kettlebellkings.com')
driver.get(url)

element_present = EC.element_to_be_clickable((By.CSS_SELECTOR, 'button[data-testid="uc-accept-all-button"]'))
WebDriverWait(driver, 30).until(element_present)
try:
    driver.find_element(By.CSS_SELECTOR, 'button[data-testid="uc-accept-all-button"]').click()
except:
    clicker = driver.find_element(By.CSS_SELECTOR, 'button[data-testid="uc-accept-all-button"]')
    driver.execute_script("arguments[0].click();", clicker)

但它只是超时了。如果我忽略预期条件:

path = "C:\Program Files (x86)\msedgedriver.exe"
driver = webdriver.Edge('www.kettlebellkings.com')
driver.get(url)

driver.find_element(By.CSS_SELECTOR, 'button[data-testid="uc-accept-all-button"]').click()

退货:
消息:没有此元素:找不到元素:{"方法":" css选择器","选择器":"按钮[数据-测试ID ="uc-accept-all-button"]"}
它似乎也不在iframe中-我在这里错过了什么?

vhmi4jdf

vhmi4jdf1#

“接受全部”Cookie按钮位于Shadow Dom内,请尝试以下代码:

shadow_root = driver.find_element(By.CSS_SELECTOR, "#usercentrics-root").shadow_root
shadow_root.find_element(By.CSS_SELECTOR, "button[data-testid='uc-accept-all-button']").click()

你可以参考下面的链接如何处理阴影dom元素:
https://www.lambdatest.com/blog/shadow-dom-in-selenium/
https://www.seleniumeasy.com/selenium-tutorials/accessing-shadow-dom-elements-with-webdriver

myzjeezk

myzjeezk2#

您可以尝试设置一个cookie,将停止弹出窗口只需接受cookie在您的正常浏览器,设置他们在程序和网站将识别它作为您/您的帐户

driver.add_cookie({"name": "key", "value": "value"})

相关问题