自動化測試學習(五) selenium命令之定位頁面元素

來源:互聯網
上載者:User

定位頁面元素

對於很多selenium命令,target域是必須的。Target在web頁面範圍內識別UI元素,它使用locatorType=location的格式。在很多情況下,locatorType可以省略,下面舉例方式來描述各種類型的locatorType.

假如,有如下一段HTML代碼:

html>    <body>    <form id= "loginForm" >    <input name= "username" type= "text"  />    <input name= "password" type= "password"  />    <input name= "continue" type= "submit" value= "Login"  />    <input name= "continue" type= "button" value= "Clear"  />    <a href= "continue.html" >Continue</a>    </form>    </body>    </html>

我們看看selenium提供了那些定位方式:

1. identifier定位

這是最普遍的一種定位方式,當不能識別為其它定位方式後,預設為dientifier定位,在這種策略下,第一個使用id的頁面元素將被識別出來,如果沒有使用指定id的元素,那麼將識別第一個名字與指定條件相符的元素。

identifier識別html各項元素的定位策略如下:

identifier=loginForm    //定位頁面元素為from

identifier=username   //定位頁面元素為username

identifier=Continue   //定位頁面元素為Continue

因為identifier定位是預設,因此“identifier=” 可以不寫。

Continue   //同樣表示定位頁面元素為Continue

2. id定位

這種定位方式比identifier定位範圍更窄,當然也更具體,如果你知道元素id特徵,就使用這種方式:

id=loginFrom   //定位頁面元素from

3. name定位

名稱定位方式將會識別第一個匹配名稱屬性的UI元素。如果多個元素擁有相同的名稱屬性,可以使用過濾器來進一步最佳化你的定位策略。預設的過濾器是Value (匹配value特徵):

name=username   //定位頁面元素為username

name=Continue  value=Clear  //定位頁面元素為Continue ,值為Clear

name=Continue  type=button  //定位頁面元素為Continue ,類型為button

提示:

上述三種定位器使得selenium可以不依賴於UI元素在頁面上的位置而進行測試。所以,當頁面結構發生變化時,測試依然可以通過。有時候,設計人員頻繁改動頁面的情況,通過id和name特徵定位元素就變的非常重要。

4. XPath定位

XPath是一種在XML文檔中定位元素的語言。因為HTML可以看做XML的一種實現,所以selenium使用者可是使用這種強大語言在web應用中定位元素。

XPath擴充了上面id和name定位方式,提供了很多種可能性,比如定位頁面上的第三個多選框。

xpath=/html/body/form[1]           //絕對路徑(html的任何輕微改變都會導致失敗)

//form[1]          //HTML中的第三個form元素

xpath=//form[@id='loginForm']        //id為loginFrom的元素

//input[@name='username']       //input元素且其name為‘username’

//form[@id='loginForm']/input[1]           //針對id為‘loginForm’的form,定位它的第一個input元素

//input[@name='continue'][@type='button']         //name為‘continue’且type為‘button’的input

//form[@id='loginForm']/input[4]        //id為‘loingForm’的form,定位它的第四個input元素。

擴充閱讀:

W3C XPath Recommendation:http://www.w3.org/TR/xpath/

XPath Tutorial: http://www.zvon.org/xxl/XPathTutorial/General/examples.html

http://www.w3.org/TR/xpath/

Firefox外掛程式,可以協助你擷取頁面元素的XPath:

XPath Checker         Firebug

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/project/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.