我对硒的第一个测试是单击网站上的按钮。我需要单击的第一个按钮是网站弹出窗口中的“是,您可以使用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
。您需要同时切换两个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()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句