Selenium:无法访问 cookie 横幅 html

问题描述

我一直在尝试使用 Selenium 访问 cookie 横幅的 html 代码。对于某些网站,我可以在 Firefox Web-Inspector 中看到 cookie 横幅 html,但是,我无法通过 Selenium 访问它。

例如https://faz.net在这里,driver.page_source 不包含 cookie 横幅的 html 代码,我也无法通过 driver.find_elements 访问它的元素(例如“ZUSTIMMEN” - 按钮。“zustimmen”的意思是“接受”)。

到目前为止我尝试过的:

    from selenium import webdriver
    driver = webdriver.Firefox()
    driver.implicitly_wait(20)
    driver.get("https://faz.net")
    print(driver.page_source)  # page source does not contain the button "ZUSTIMMEN"
    print(driver.find_elements_by_xpath('//button[text()="ZUSTIMMEN"]'))
    driver.execute_script("arguments[0].click();",webdriverwait(driver,20).until(EC.element_to_be_clickable((By.XPATH,'//button[text()=ZUSTIMMEN"]'))))

我做错了什么?

解决方法

那个按钮 ZUSTIMMENiframe 中。您需要将驱动程序焦点切换到 iframe,如下所示:

driver.get("https://faz.net")
wait = WebDriverWait(driver,10)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[id^='sp_message_iframe']")))
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"button[title='ZUSTIMMEN']"))).click()

进口:

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

完成 iframe 后,您可以像这样切换到默认内容:

driver.switch_to.default_content()
,

该元素位于 iframe 内。
您必须切换到 iframe 才能访问该元素。
像这样:

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

driver = webdriver.Firefox()
driver.get("https://faz.net")

WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[contains(@title,'SP')]"))) 

现在您可以点击 cookie 按钮以关闭它

wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR,"[title='ZUSTIMMEN']"))).click()

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...