首页 > 解决方案 > 如何关闭硒中的隐私同意覆盖?

问题描述

这是我的代码:

from selenium import webdriver

from selenium.webdriver.common.by import By


op_path: str = r"D:\Coding\Python\Projekte\Minecraft Updater\stuff\chromedriver.exe"

driver=webdriver.Chrome(op_path)

driver.get('https://www.curseforge.com/minecraft/mc-mods')



driver.implicitly_wait(10)

driver.find_element(By.XPATH, '//button[text()="Akeptieren"]').click()

我正在尝试抓取https://www.curseforge.com/minecraft/mc-mods,但是该页面首先要求我同意某种 cookie 隐私的事情。我为“接受”按钮尝试的所有定位器似乎都不起作用。在尝试搜索按钮之前,我确保覆盖层已经弹出,但即便如此,它也会引发“没有这样的元素”错误。

这是接受按钮的 HTML 部分:

<button tabindex="0" title="Akzeptieren" aria-label="Akzeptieren" class="message-component message-button no-children buttons-row" path="[0,3,1]" style="padding: 10px 18px; margin: 10px; border-width: 1px; border-color: rgb(37, 53, 81); border-radius: 0px; border-style: solid; font-size: 14px; font-weight: 700; color: rgb(37, 53, 81); font-family: arial, helvetica, sans-serif; width: auto; background: rgb(255, 255, 255);">Akzeptieren</button>

我是 HTML 和 selenium 的新手,所以我很难理解如何点击这个该死的按钮!

标签: pythonseleniumselenium-chromedriver

解决方案


您的接受按钮位于 iframe 中。

在 Selenium 中,您需要切换到该框架以访问内容,然后在完成后切换回来。为了允许同步问题,最好使用 webdriver 等待。有关 Selenium 等待的更多信息,请点击此处

这对我有用


driver = webdriver.Chrome() 
driver.get('https://www.curseforge.com/minecraft/mc-mods')

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH, "//iframe[contains(@id,'sp_message_iframe')]")))
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Akeptieren']"))).click()
driver.switch_to_default_content()

##continue with your script

selenium 文档建议不要混合隐式和显式等待。如果您更喜欢使用隐式方法,这也可以:

driver = webdriver.Chrome() 
driver.get('https://www.curseforge.com/minecraft/mc-mods')
driver.implicitly_wait(10)

iframe = driver.find_element_by_xpath("//iframe[contains(@id,'sp_message_iframe')]")
driver.switch_to.frame(iframe)
driver.find_element_by_xpath("//button[text()='Akeptieren']").click()
driver.switch_to_default_content()

##continue with your script

推荐阅读