python - 如何关闭硒中的隐私同意覆盖?
问题描述
这是我的代码:
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 的新手,所以我很难理解如何点击这个该死的按钮!
解决方案
您的接受按钮位于 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
推荐阅读
- sql-server - 使用“In”的 SQL 到实体框架
- javascript - 使用 requestAnimationFrame 添加限制?
- batch-file - 杀死从另一个 cmd 框卡住的批处理文件
- c# - 如何创建一个带有问题的无限循环,该问题在回答时将答案分类为 3 个不同数组中的 1 个?
- extjs - 浮动经典树列表在单击以展开时关闭
- python - 如何在 date_range 函数生成的日期时间中应用条件?
- python - 运行 K_Means 聚类算法并得到奇怪的结果
- python - 如何将用户输入保存在实际 Python3 脚本文件的列表中
- node.js - Yarn - 如何设置 Yarn 使用 cookie
- cmake - 使用带有 check_c_source_runs() 或 try_run() 的接口库