Python selenium 如何点击iframe中的元素?

Python selenium How to click an element in iframe?

我对 selenium 的第一个测试是单击网站上的按钮。我需要单击的第一个按钮是网站弹出窗口中的“是的,您可以使用 cookie”按钮。但是即使我添加了等待线,selenium 似乎也找不到该按钮。我也尝试了弹出窗口中的其他按钮,但我的 element_to_be_clickable 可以找到其中 none 个按钮。该元素在 iframe 中,所以我想我必须更改它,但似乎我做错了什么。

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

driver_path = "D:/Python/learning_webclicker/firefox_driver/geckodriver.exe"
firefox_path = "C:/Program Files/Mozilla Firefox/firefox.exe"
option = webdriver.FirefoxOptions()
option.binary_location = firefox_path
driver = webdriver.Firefox(executable_path=driver_path, options=option)

url = "https://web.de/"
driver.get(url)

WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it(driver.find_element_by_xpath("/html/body/div[2]/iframe")))
#I tried to find the "save-all-conditionally"-element with lots of different methods:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "save-all-conditionally"))).click()
#WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, """//*[@id="save-all-conditionally"]"""))).click()
#WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "save-all-conditionally")))
# ...

这会引发错误

selenium.common.exceptions.TimeoutException: Message:

如果我尝试在更改为 iframe 后直接单击按钮(或不检查 iframe),那么我会得到

driver.implicitly_wait(10)
element=driver.find_element_by_xpath("""//*[@id="save-all-conditionally"]""")
element.click()
>>> selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="save-all-conditionally"]

我想,我不在 iframe 中(尽管 frame_to_be_available_and_switch_to_it 不会 return 错误),但我不确定 how/what/why。

您要查找的元素在nested iframe内。你需要同时切换 内嵌框架。

使用以下 css 选择器来识别 iframe

WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[name='landingpage']"))) 
WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[src*='plus.web.de']")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "save-all-conditionally"))).click()

或使用下面的 xpath 来识别 iframe。

WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@name='landingpage']"))) 
WebDriverWait(driver,10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[contains(@src,'plus.web.de')]")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "save-all-conditionally"))).click()