Selenium定位元素

來源:互聯網
上載者:User

標籤:

Commands (命令)

  • Action
    對目前狀態進行操作
    失敗時,停止測試
  • Assertion
    校正是否有產生正確的值
  • Element Locators
    指定HTML中的某元素
  • Patterns
    用於模式比對

1. Element Locators (元素定位器)

  • id=id
    id locator 指定HTML中的唯一id的元素
  • name=name
    name locator指定 HTML中相同name的元素中的第一個元素
  • identifier=id
    identifier locator 首先尋找HTML是否存在該id的元素, 若不存在,尋找第一個該name的元素
  • dom=javascriptExpression
    dom locator用JavaScript運算式來定位HTML中的元素,注意必須要以"document"開頭
    例如:
    dom=document.forms[‘myForm‘].myDropdown
    dom=document.images[56]
  • xpath=xpathExpression
    xpath locator用 XPath 運算式來定位HTML中的元素,必須注意要以"//"開頭
    例如:
    xpath=//img[@alt=‘The image alt text‘]
    xpath=//table[@id=‘table1‘]//tr[4]/td[2]
  • link=textPattern
    link locator 用link來選擇HTML中的串連或錨元素
    例如:
    link=The link text
  • 在沒有locator前序的情況下 Without a locator prefix, Selenium uses:
    如果以"document."開頭,則預設是使用 dom locator,如果是以"//"開頭,則預設使用xpath locator,其餘情況均認作identifier locator

2. String Matching Patterns (字串匹配模式)

  • glob:patthern
    glob模式,用萬用字元"*"代表任意長度字元,"?"代表一個字元
  • regexp:regexp
    Regex模式,用JavaScriptRegex的形式匹配字串
  • exact:string
    精確匹配模式,精確匹配整個字串,不能用萬用字元
  • 在沒有指定字串匹配前序的時候,selenium 預設使用golb 匹配模式

3. Select Option Specifiers (Select選項指定器)

  • label=labelPattern
    通過匹配選項中的文本指定選項
    例如:label=regexp:^[Oo]ther
  • value=valuePattern
    通過匹配選項中的值指定選項
    例如:value=other
  • id=id
    通過匹配選項的id指定選項
    例如: id=option1
  • index=index
    通過匹配選項的序號指定選項,序號從0開始
    例如:index=2
  • 在沒有選項選擇前序的情況下,預設是匹配選項的文本
Actions

描述了使用者所會作出的操作。
Action 有兩種形式: action和actionAndWait, action會立即執行,而actionAndWait會假設需要較長時間才能得到該action的相響,而作出等待,open則是會自動處理等待時間。

  • click
    click(elementLocator)
    - 點擊串連,按鈕,複選和單選框
    - 如果點擊後需要等待響應,則用"clickAndWait"
    - 如果是需要經過JavaScript的alert或confirm對話方塊後才能繼續操作,則需要調用verify或assert來告訴Selenium你期望對對話方塊進行什麼操作。
    click          aCheckbox  
    clickAndWait submitButton  
    clickAndWait

    anyLink

     

     

     

     selenium.Click("id=login");

 

  • open
    open(url)
    - 在瀏覽器中開啟URL,可以接受相對和絕對路徑兩種形式
    - 注意:該URL必須在與瀏覽器相同的安全限定範圍之內
    open /mypage  
    open    http://localhost/  

     

      selenium.Open("/");

 

  • type
    type(inputLocator, value)
    - 類比人手的輸入過程,往指定的input中輸入值
    - 也適合給複選和單選框賦值
    - 在這個例子中,則只是給鉤選了的複選框賦值,注意,而不是改寫其文本
    type nameField    John Smith
    typeAndWait  textBoxThatSubmitsOnChange    newValue

     

      selenium.Type("id=UserName", userName);

 

  • select
    select(dropDownLocator, optionSpecifier)
    - 根據optionSpecifier選項選取器來選擇一個下拉式功能表選項
    - 如果有多於一個選取器的時候,如在用萬用字元模式,如"f*b*",或者超過一個選項有相同的文本或值,則會選擇第一個匹配到的值
    select  dropDown Australian Dollars
    select  dropDown index=0
    selectAndWait currencySelector       value=AUD
    selectAndWait       currencySelector label=Auslian D*rs
  •  goBack,close
    goBack()
    類比點擊瀏覽器的後退按鈕

   selenium.GoBack();

 

  • close()
    類比點擊瀏覽器關閉按鈕


   selenium.Close();

 

  • selectWindow
    select(windowId)
    - 選擇一個快顯視窗
    - 當選中那個視窗的時候,所有的命令將會轉移到那視窗中執行
    selectWindow myPopupWindow  
    selectWindow null  
  • pause
    pause(millisenconds)
    - 根據指定時間暫停Selenium指令碼執行
    - 常用在調試指令碼或等待伺服器段響應時
    pause 5000  
    pause 2000  
  • fireEvent
     fireEvent(elementLocatore,evenName)
    類比頁面元素事件被啟用的處理動作
    fireEvent textField focus
    fireEvent dropDown blur
  • waitForCondition
    waitForCondition(JavaScriptSnippet,time)
    - 在限定時間內,等待一段JavaScript代碼返回true值,逾時則停止等待
    waitForCondition var value=selenium.getText("foo"); value.match(/bar/); 3000
  • waitForValue
    waitForValue(inputLocator, value)
    - 等待某input(如hidden input)被賦予某值,
    - 會輪流檢測該值,所以要注意如果該值長時間一直不賦予該input該值的話,可能會導致阻塞
    waitForValue finishIndication isfinished
         
  • store,stroreValue
    store(valueToStore, variablename)
    儲存一個值到變數裡。
    該值可以由自其他變數組合而成或通過JavaScript運算式賦值給變數
    store Mr John Smith fullname
    store $.{title} $.{firstname} $.{suname} fullname
    store javascript.{Math.round(Math.PI*100)/100} PI
    storeValue inputLocator variableName

    把指定的input中的值儲存到變數中

    storeValue userName userID
    type userName $.{userID}
  • storeText, storeAttribute
    storeText(elementLocator, variablename)
    把指定元素的文本值賦予給變數
    storeText currentDate expectedStartDate
    verifyValue startDate $.{expectedStartDate}

    storeAttribute(.{}[email protected],variableName.{)
    把指定元素的屬性的值賦予給變數

    storeAttribute [email protected]  classOfInput1
    verifyAttribute [email protected] $.{classOfInput1}

 

 

storeAttribute  target: aa@bb儲存元素  value: 變數    儲存aa的bb值到變數中

String taskName = selenium.GetAttribute("[email protected]");
Console.WriteLine(taskName);

將id為minblogBody的defvalue值儲存到taskName中,並列印taskName

 

storteText  

target://*[@id=‘ul_80185794-3209-4e6b-8cea-af39348c5cdd‘]/li[1]/span[6]/a[1]

value:bind

echo

${bind}

將路徑為target裡的值儲存在bind變數中,並輸出bind的值。

  • chooseCancel.., answer..
    chooseCancelOnNextConfirmation()
    - 當下次JavaScript彈出confirm對話方塊的時候,讓selenium選擇Cancel
    - 如果沒有該命令時,遇到confirm對話方塊Selenium預設返回true,如手動選擇OK按鈕一樣
    chooseCancelOnNextConfirmation     

    - 如果已經運行過該命令,當下一次又有confirm對話方塊出現時,也會同樣地再次選擇Cancel
    answerOnNextPrompt(answerString)
    - 在下次JavaScript彈出prompt提示框時,賦予其anweerString的值,並選擇確定

    answerOnNextPrompt Kangaroo  
Assertions

允許使用者去檢查目前狀態。兩種模式: Assert 和 Verify,當Assert失敗,則退出測試;當Verify失敗,測試會繼續運行。

  • assertLocation, assertTitle
    assertLocation(relativeLocation)
    判斷當前是在正確的頁面
    verifyLocation /mypage  
    assertLocation /mypage  
  • assertTitle(titlePattern)
    檢查當前頁面的title是否正確
    verifyTitle My Page  
    assertTitle My Page  
  • assertValue
    assertValue(inputLocator, valuePattern)
    - 檢查input的值
    - 對於 checkbox或radio,如果已選擇,則值為"on",反之為"off"
    verifyValue nameField John Smith
    assertValue document.forms[2].nameField John Smith
  • assertSelected, assertSelectedOptions
    assertSelected(selectLocator, optionSpecifier)
    檢查select的下拉式功能表中選中的選型是否和optionSpecifer(Select選擇選項器)的選項相同
    verifySelected dropdown2 John Smith
    verifySelected dorpdown2 value=js*123
    assertSelected document.forms[2].dropDown label=J*Smith
    assertSelected document.forms[2].dropDown index=0
  • assertSelectOptions(selectLocator, optionLabelList)
    - 檢查下拉式功能表中的選項的文本是否和optionLabelList相同
    - optionLabelList是以逗號分割的一個字串
    verifySelectOptions dropdown2 John Smith,Dave Bird
    assertSelectOptions document.forms[2].dropdown Smith,J,Bird,D
  • assertText
    assertText(elementLocator,textPattern)
    - 檢查指定元素的文本
    - 只對有包含文本的元素生效
    - 對於Mozilla類型的瀏覽器,用textContent取元素的文本,對於IE類型的瀏覽器,用innerText取元素文本
    verifyText statusMessage Successful
    assertText //div[@id=‘foo‘]//h1 Successful
  • assertTextPresent, assertAttribute
    assertTextPresent(text)
    檢查在當前給使用者顯示的頁面上是否有出現指定的文本
    verifyTextPresent You are now logged in  
    assertTextPresent You are now logged in  

 

selenium.IsTextPresent("beisen:分享測試01")

 

  • assertAttribute(.{}[email protected]{, ValuePattern)
    檢查當前指定元素的屬性的值
    verifyAttribute [email protected] bigAndBlod
    assertAttribute document.images[0]@alt alt-text
    verifyAttribute //img[@id=‘foo‘]/alt alt-text
  • assertTextPresent, etc.
    assertTextPresent(text)
    assertTextNotPresent(text)
    assertElementPresent(elementLocator)
    verifyElementPresent submitButton  
    assertElementPresent //img[@alt=‘foo‘]   assertElementNotPresent(elementLocator)
  • assertTable
    assertTable(cellAddress, valuePattern)
    - 檢查table裡的某個cell中的值
    - cellAddress的文法是tableName.row.column, 注意行列序號都是從0開始
    verifyTable myTable.1.6 Submitted
    assertTable results0.2 13
  • assertVisible, nonVisible
    assertVisible(elementLocator)
    - 檢查指定的元素是否可視的
    - 隱藏一個元素可以用設定css的‘visibility‘屬性為‘hidden‘,也可以設定‘display‘屬性為‘none‘
    verfyVisible postcode  
    assertVisible postcode  
  • assertNotVisible(elementLocator)
    verfyNotVisible postcode  
    assertNotVisible postcode  
  • Editable, non-editable
    assertEditable(inputLocator)
    檢查指定的input是否可以編輯
    verifyEditable shape  
    assertEditable colour  
  • assertNotEditable(inputLocator)
    檢查指定的input是否不可以編輯
  • assertAlert
    assertAlert(messagePattern)
    - 檢查JavaScript是否有產生帶指定message的alert對話方塊
    - alert產生的順序必須與檢查的順序一致
    - 檢查alert時會產生與手動點擊‘OK‘按鈕一樣的效果。如果一個alert產生了,而你卻沒有去檢查它,selenium會在下個action中報錯。
    - 注意:Selenium 不支援 JavaScript 在onload()事件時調用alert();在這種情況下,Selenium需要你自己手動來點擊OK.
  • assertConfirmation
    assertConfirmation(messagePattern)
    - 檢查JavaScript是否有產生帶指定message的confirmation對話方塊和alert情況一樣,confirmation對話方塊也必須在它們產生的時候進行檢查
    - 預設情況下,Selenium會讓confirm() 返回true, 相當於手動點擊Ok按鈕的效果。你能夠通過chooseCancelOnNextConfirmation命令讓confirm()返回false.同樣地,如果一個cofirmation對話方塊出現了,但你卻沒有檢查的話,Selenium將會在下個action中報錯
    - 注意:在Selenium的環境下,confirmation對話方塊框將不會再出現彈出顯式對話方塊
    - 注意:Selenium不支援在onload()事件時調用confirmation對話方塊,在這種情況下,會出現顯示confirmatioin對話方塊,並需要你自己手動點擊。
  • assertPrompt
    assertPrompt(messagePattern)
    - 檢查JavaScript是否有產生帶指定message的Prompt對話方塊
    - 你檢查的prompt的順序Prompt對話方塊產生的順序必須相同
    - 必須在verifyPrompt之前調用answerOnNextPrompt命令
    - 如果prompt對話方塊出現了但你卻沒有檢查,則Selenium會在下個action中報錯
    answerOnNextPrompt Joe  
    click id=delegate  
    verifyPrompt Delegate to who?  
Parameters and Variables

參數和變數的聲明範圍由簡單的賦值到JavaScript運算式賦值。
Store,storeValue 和storeText 為下次訪問儲存值。
在Selenium內部是用一個叫storeVars的map來儲存變數名。

    • Variable Substitution 變數替換
      提供了一個簡單的方法去訪問變數,文法 $.{xxx}
      store Mr title
      storeValue nameField surname
      store $.{title} $.{suname} fullname
      type textElement Full name is: $.{fullname}
    • JavaScript Evaluation JavaScript賦值
      你能用JavaScript來構建任何你所需要的值。
      這個參數是以javascript開頭,文法是 javascript.{‘with a trailing‘}。
      可以通過JavaScript運算式給某元素賦值。
      store javascript.{‘merchant‘+(new Date()).getTime()} merchantId
      type textElement javascript.{storedVars[‘merchantId‘].toUpperCase()}
      來源: <http://sariyalee.iteye.com/blog/1743350> 

Selenium定位元素

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.