我已經寫了一個腳本來測試一個涉及數據輸入&幾個頁面的過程,但寫完後我發現了從javascript生成的主要內容形式&。 以下是我寫的腳本的一個片段,在初始鏈接之後,內容由JS(它的第一個Python腳本,所以原諒任何錯誤)生成;在Selernium中使用Python生成的Javascript內容導航?
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。另外,如果你能找到一種方法,而不是通過文本獲取元素,那會更好。通過文本內容識別元素通常是最脆弱的方式。 – 2012-03-01 14:30:15
謝謝,這些進口中的一些是我今天上午運行的例子,以便掌握所有這些。我很想避免通過文本查找,但不幸的是,該產品沒有開發任何這方面的考慮,所以現在鏈接沒有ID或名稱來選擇它。一旦我有了一個工作理念,我需要儘可能地改變一些事情。 – 2012-03-01 14:39:42
您應該可以使用XPath,CSS或DOM來查找頁面上任何不同的實體,並可以使用或不使用唯一的ID。最糟糕的情況是從身體開始下來,但應該有一個更快的方法。另外,至於你的問題,你有沒有嘗試過看selenium IDE如何識別你的JS元素的快速和骯髒的方法? – 2012-03-01 14:53:21