如何解决Python selenium 如何点击 iframe 中的元素?
我对 selenium 的第一个测试是单击网站上的一个按钮。我需要单击的第一个按钮是网站弹出窗口中的“是的,您可以使用 cookie”按钮。但是即使我添加了等待线,硒似乎也找不到那个按钮。我也尝试了弹出窗口中的其他按钮,但我的 element_to_be_clickable 都找不到它们。该元素在 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 没有返回错误),但我不确定如何/什么/为什么。
解决方法
您正在关注的元素在 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,"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,"//iframe[contains(@src,'plus.web.de')]")))
WebDriverWait(driver,"save-all-conditionally"))).click()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。