Selenium - 如何调试iframe的超时>输入字段?

时间:2014-09-16 05:57:21

标签: python iframe selenium

我很难为Instagram网页登录编写Selenium WebDriver脚本。我想我切换到了合适的iframe但WebDriver在找到用户输入字段时会保持超时。

来自Instagram网站的相关来源:

https://instagram.com/accounts/login/
<iframe class="hiFrame" data-reactid=".0.0.0.1.0.1.0.0.$frame"    src="https://instagram.com/accounts/login/ajax/?targetOrigin=https%3A%2F%2Finstagram.com" scrolling="no" seamless="">
<!DOCTYPE html>
<html class="hl-en not-logged-in " lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<body class="LoginFormChrome ">
<div class="LoginFormPage" data-reactid=".0">
<form data-reactid=".0.0">
<p class="lfField" data-reactid=".0.0.0">
<label class="lfFieldLabel" data-reactid=".0.0.0.0">
<input class="lfFieldInput" type="text" data-reactid=".0.0.0.1" value="" autocorrect="false" autocapitalize="false" maxlength="30" name="username">
</p>

来自Selenium脚本的来源:

login_url = 'https://instagram.com/accounts/login/'
profile_url = '<path_firefix_profile>'
user = '<user_name>'
#login
my_profile = FirefoxProfile(profile_url)
self.driver = webdriver.Firefox(my_profile)

self.driver.get(login_url)
self.driver.implicitly_wait(10)
my_iframe = self.driver.find_element_by_css_selector("iframe.hiFrame")
#my_iframe = self.driver.find_element_by_css_selector("iframe:nth-of-type(1)")
#my_iframe = self.driver.find_element_by_tag_name("iframe")
self.driver.switch_to_frame(my_iframe)
try:
    element = WebDriverWait(self.driver, 30).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input[name='username']")))
    user_input = self.driver.find_element_by_css_selector("input[name='username']")
    user_input.send_keys(user)
finally:
    print('user name input appeared')

结果: WebDriver导致此错误: 在setUp中输入第51行“instagram_firefox.py”     element = WebDriverWait(self.driver,45).until(EC.visibility_of_element_located((By.CSS_SELECTOR,“input [name ='username']”)))   文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/support/wait.py”,第71行,直到     提出TimeoutException(消息)

我试图验证输入字段的css选择器是否正确。在页面https://instagram.com/accounts/login/上,FireFox FireFinder无法识别我使用的css选择器。但是,如果我打开另一个带有iframe源代码的标签https://instagram.com/accounts/login/ajax/?targetOrigin=https%3A%2F%2Finstagram.com,则Firefinder会识别我使用的css选择器。这是否意味着我需要手动获取iframe源的url,还是应该在WebDriver切换到iframe时自动完成?

1 个答案:

答案 0 :(得分:1)

我们应该先等待div微调元素消失,然后我们可以检索你需要的iframe:

user = "user"
self.driver.get("https://instagram.com/accounts/login/")
#Wait for spinner to disappear
WebDriverWait(self.driver, 10).until(EC.invisibility_of_element_located((By.CSS_SELECTOR, "div.liSpinnerLayer")))
#Get iframe and switch to it
my_iframe = self.driver.find_element_by_css_selector("iframe.hiFrame")
self.driver.switch_to_frame(my_iframe)
element = WebDriverWait(self.driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "input[name='username']")))
element.send_keys(user)