首页 > 解决方案 > Selenium 错误:元素不可交互(coockie 和其他弹出窗口)

问题描述

我正在尝试使用 selenium 按下按钮,因为之后我需要检查网站的完整 html。这是我正在使用的代码:

driver = webdriver.Chrome()
driver.get('https://www.quattroruote.it/listino/audi/a4-allroad')
time.sleep(10)
html = driver.find_element_by_id('btnallestimenti')
html.click()

但我收到此错误:selenium.common.exceptions.ElementNotInteractableException:消息:元素不可交互

当页面打开时,会显示 cookie 和其他内容,有没有办法阻止所有这些,以便我可以处理 html?

非常感谢!

标签: pythonhtmlseleniumbeautifulsoupinspect

解决方案


如您所见,“cookies”横幅本身就是一个 HTML 元素,它包含一个可以单击的“关闭”(“Chiudi”)按钮。

如果您检查页面源代码,您会发现与该按钮相关的代码:

<button type="button" class="iubenda-cs-close-btn" tabindex="0" role="button" aria-pressed="false" style="font-size:16px!important;">Chiudi</button>

您的脚本需要修改以通过可见文本(使用 XPath)搜索元素并单击它以关闭横幅:

close_button = driver.find_element_by_xpath("//*[text()='Chiudi']")

close_button.click()

我可以看到这种横幅出现了 2 次(一个用于 cookie,一个用于“Informativa”),但是一旦您单击此横幅,您就会被重定向到正确的页面。

当然,您需要测试您的脚本并根据页面的行为对其进行调整。

另外,请注意,每次页面因开发人员更改而更改时,您的脚本都会中断,您需要重新调整它。

编辑

在此处发布完整代码,尝试使用它并从此处继续:

import time
from selenium.webdriver import Chrome

driver = Chrome()

driver.get("https://www.quattroruote.it/listino/audi/a4-allroad")
time.sleep(6)

driver.find_element_by_xpath("//button[text()='Accetta']").click()
time.sleep(6)

driver.switch_to.frame("promo-premium-iframe")
driver.find_element_by_xpath("//a[normalize-space()='Non sono interessato']").click()
time.sleep(6)

driver.switch_to.default_content()

driver.find_element_by_id("btnallestimenti").click()

input()

推荐阅读