【发布时间】:2012-03-01 14:04:25
【问题描述】:
我编写了一个脚本来测试涉及数据输入和多个页面的过程,但是在编写之后我发现表单和主要内容是从 javascript 生成的。 下面是我写的脚本的sn-p,在那个初始链接之后,内容是由JS生成的(这是我的第一个python脚本,请原谅任何错误);
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
browser = webdriver.Firefox()
browser.get('http://127.0.0.1:46727/?ajax=1')
assert "Home" in browser.title
# Find and click the Employer Database link
empDatabaseLink = browser.find_element_by_link_text('Employer Database')
click = ActionChains(browser).click(on_element = empDatabaseLink)
click.perform()
# Content loaded by the above link is generated by the JS
# Find and click the Add Employer button
addEmployerButton = browser.find_element_by_id('Add Employer')
addEmployer = ActionChains(browser).click(on_element = addEmployerButton)
addEmployer.perform()
browser.save_screenshot(r'images\Add_Employer_Form.png')
# Input Employer name
employerName = browser.find_element_by_id('name')
employerName.send_keys("Selenium")
browser.save_screenshot(r'images\Entered_Employer_Name.png')
# Move to next
nextButton = broswer.find_element_by_name('button_next')
moveForward = ActionChains(browser).click(on_element = nextButton)
# Move through various steps
# Then
# Move to Finish
moveForward = ActionChains(browser).click(on_element = nextButton)
如何访问不在源中的页面元素?我一直在环顾四周并找到了 GetEval,但没有找到任何我可以使用的东西:/
【问题讨论】:
-
几点提示,您应该可以只使用 addEmployerButton.click() 而不是更复杂(有些人认为不必要)的 ActionChains 方法。您的代码似乎也不需要 Keys 或导入的 Exception 。另外,如果你能找到一种方法,而不是通过文本获取元素,那就更好了;通过文本内容识别元素通常是最脆弱的方法。
-
谢谢,其中一些导入是我今天早上运行的示例中留下的,以便掌握所有这些。而且我很想避免通过文本进行定位,但不幸的是,该产品的开发并未考虑到这些,因此目前该链接没有可供选择的 ID 或名称。一旦我有了一个可行的概念,我需要尽可能地改变一些东西。
-
您应该能够使用 XPath、CSS 或 DOM 来定位页面上的任何不同实体,无论是否具有唯一 ID。最坏的情况是从身体开始向下工作,但应该有更快的方法。另外,关于您的问题,您是否尝试过快速而肮脏的方法来查看 selenium IDE 如何识别您的 JS 元素?
-
XPath 是我最好的新朋友!谢谢@sr2222 - 我刚刚使用 XPath 找到了链接,然后找到了我无法找到的 addEmployerButton。
标签: javascript python selenium webdriver