切换到Selenium中包含登录提示的框架
问题描述:
我正尝试使用Selenium登录到ESPN。过去的解决方案详述如下:here。为了登录,我需要找到具有用户名和密码字段的框架并切换到该框架。不幸的是,该框架的数字指标并不总是相同的。我决定尝试所有这些,但只要我切换到一帧,切换到下一个失败,selenium.common.exceptions.StaleElementReferenceException: Message: The element reference of <iframe class="ob-pifr"> stale: either the element is no longer attached to the DOM or the page has been refreshed
。所以我在寻找切换到Selenium中包含登录提示的框架
- 来切换图像,而不
StaleElementReferenceException
- 一种方法来检查帧是否是一个我想之前,我切换到它
- 一些其他的解决方案的一种方式,但我ð喜欢的东西内省的魔法(大概脆弱)公式像“它总是从最终的第3张)
下面是一些示例代码,导致StaleElementReferenceException
:
from time import sleep
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Firefox(executable_path = '/usr/local/bin/geckodriver')
driver.get("http://games.espn.go.com/ffl/signin")
WebDriverWait(driver, 1000).until(EC.presence_of_all_elements_located((By.XPATH,"(//iframe)")))
elem = None
frms = driver.find_elements_by_xpath("(//iframe)")
print("Found {} frames", len(frms)) # Varies from 6 to 8
for count, frm in enumerate(frms):
print("Trying frm[{}]".format(count))
driver.switch_to.frame(frm)
sleep(2)
try:
# The command below will fail the second time around with
# `either the element is no longer attached to the DOM or the page has been refreshed`
elem = driver.find_element_by_xpath("(//input)[1]")
except NoSuchElementException:
pass
else:
break
答
帧ID是disneyid-iframe
其所以首先打开登录弹出你需要切换到它
driver.switch_to_frame(driver.find_element_by_id("disneyid-iframe"))
,然后执行类似
driver.find_element_by_xpath("//input[@type='email']").send_keys("emailid")
driver.find_element_by_xpath("//input[@type='password']").send_keys("password")
其他方式的SendKeys帧切换时ExplicitWait
。它等到框架可一旦有那么它得到
wait = WebDriverWait(driver, 60)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "disneyid-iframe")))
您的最终代码转换将是:
from time import sleep
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Firefox(executable_path = '/usr/local/bin/geckodriver')
driver.get("http://games.espn.go.com/ffl/signin")
wait = WebDriverWait(driver, 60)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "disneyid-iframe")))
driver.find_element_by_xpath("//input[@type='email']").send_keys("emailid")
driver.find_element_by_xpath("//input[@type='password']").send_keys("password")
driver.find_element_by_xpath("//button[@type='submit']").click()
注意:请检查语法按Python的。