您的位置:軟件測試 > 開源軟件測試 > 開源功能測試工具 > Selenium
在Selenium WebDriver中使用By.Xpath快速定位頁面元素
作者:網(wǎng)絡(luò)轉(zhuǎn)載 發(fā)布時間:[ 2014/1/23 9:40:13 ] 推薦標簽:Selenium WebDriver 頁面

driver.findElement(By.xpath("//input[@name='pass']")).clear();

driver.findElement(By.xpath("//input[@name='pass']")).sendKeys("密碼");

driver.findElement(By.xpath("//input[@id= passwords]")).clear();

driver.findElement(By.xpath("//input[@id= passwords]")).sendKeys("123456");

重新回放,時間仍然很長,看來通過一個元素鍵值對定位是不可靠的,那能不能通過多個元素呢?跟QTP中的高級描述性編程一樣。那xpath的語法是什么,多個元素鍵值對怎么連接到一起呢?

 

首先查找name=pass的這個元素的另外一個元素鍵值對:class= textfild,用這兩個定位一下試試看。

driver.findElement(By.xpath("//input[@name='pass'and@class=’ textfild’]")).clear();

driver.findElement(By.xpath("//input[@name='pass'and@class=’ textfild’]")).sendKeys("密碼");

driver.findElement(By.xpath("//input[@id= passwordsand@class=’ textfild required’]")).clear();

driver.findElement(By.xpath("//input[@id=passwordsand@class=’textfild required’]")).sendKes(“12..”);

再回訪,速度果然快了,很快便識別到了密碼框的位置,并且進行了輸入。

 

關(guān)于xpath查找元素還可以通過contains(一個字符串查找函數(shù))來實現(xiàn),語法是

//input[contains(@id,vakue)andcontains(@id,value)],此中的id和value是定位input元素的鍵值對

 

例如:

//input[contains(@class,'textfild') and contains(@name,'pass')]

 

那后經(jīng)過整合和簡化,4句的代碼可簡化為以下兩句

driver.findElement(By.xpath("//input[contains(@class,'textfild')andcontains(@name,'pass')]")).clear();

driver.findElement(By.xpath("//input[@id='passwords'and@class='textfild required'and@type='password']")).sendKeys("123456");

 

為什么能簡化為2行呢,看上面的截圖,其實一上來的時候密碼框里有“密碼”兩個字,當鼠標移入密碼框獲取焦點以后,“密碼”文字消失,用戶可以輸入自己真正的密碼。所以

driver.findElement(By.xpath("//input[@name='pass'and@class=’ textfild’]")).sendKeys("密碼");

這句話是我們不需要的。因為當密碼框獲取焦點以后,“密碼”文字消失了,所以下面的清空也沒有必要存在了

driver.findElement(By.xpath("//input[@id= passwordsand@class=’ textfild required’]")).clear();

這樣,代碼簡化了。

回放,一切ok。

上一頁12下一頁
軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd