需要一些关于在Python / Selenium WebDriver中使用JavaScript的建议

时间:2013-09-09 21:20:09

标签: javascript python selenium-webdriver

我一整天都在搜索stackoverflow来回答这个问题。我正在尝试使用Selenium WebDriver点击进入iframe并填写注册表单上的字段。由于Python本身返回错误“无法定位元素”,我现在正尝试使用JavaScript进入该领域。

新错误是“raise exception_class(message,screen,stacktrace) selenium.common.exceptions.WebDriverException:消息:u'document.getElementById(...)为null';“

关于我做错的任何建议?

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0

import string
import random
def id_generator(size=6, chars=string.ascii_uppercase):
     return ''.join(random.choice(chars) for x in xrange(size))

# Create a new instance of the Firefox driver
driver = webdriver.Firefox()

driver.get("http://bostinno.streetwise.co")

driver.find_element_by_link_text("Sign-up").click()

WebDriverWait(driver, 30)

driver.execute_script("document.getElementById('User_firstName').click()")

type(id_generator())

1 个答案:

答案 0 :(得分:2)

这应该可以使用Selenium API switchto(),这不需要任何JavaScript。它可能看起来像这样:

# move into the iframe
iframe = driver.find_elements_by_tag_name('iframe')[0]
driver.switch_to_frame(iframe)

# interact with your element inside the iframe
driver.find_element_by_link_text("Sign-up").click()
driver.find_element_by_id("User_firstName").click()

# do any other steps you need...

# move back out of iframe
driver.switch_to_default_content()