【发布时间】:2021-05-12 04:35:14
【问题描述】:
我对 selenium 的第一个测试是单击网站上的按钮。我需要单击的第一个按钮是网站弹出窗口中的“是的,您可以使用 cookie”按钮。但似乎 selenium 没有找到那个按钮,即使我添加了一条等待线。我也尝试了弹出窗口中的其他按钮,但我的 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 没有返回错误),但我不确定如何/什么/为什么。
【问题讨论】:
-
ATM 太忙,但请尝试
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it(By.XPATH, "/html/body/div[2]/iframe"))。您可能需要额外的导入,即from selenium.webdriver.common.by import By。 -
谢谢,但我得到了相同的结果(我在 (By.XPATH, "string") 周围添加了一个元组以避免另一个错误)
标签: python selenium xpath css-selectors webdriverwait