2012-04-09 27 views
1

我試圖擺脫的元素列表子元素和替代 在列表中每個項目的回報子元素的值 - >它只返回 第一項。的webdriver獲取元件與元件阻擋

List<WebElement> allAccoElements = driver.findElements(By.xpath("//ul[@id='ListerContainer']//li[@class='lister-item']//div[@class='lister-item-content']")); 
// Found 10 items 

for (WebElement element: allAccoElements){ 
System.out.println(element.findElement(By.xpath("//img[@class='image-base']")).getAttribute("id")); 
//For loop will print "id" of first element 10 times, why I can't to get access to other Elements in list? 
} 

Print always return id of first element in list, can anyone suggest me, how I can find child element of each element in list? 

相反,如果我用下面的代碼類似的解決方法,一切工作正常。

List<WebElement> allAccoElements = driver.findElements(By.xpath("//ul[@id='ListerContainer']//li[@class='lister-item']//div[@class='lister-item-content']//img[@class='image-base']")); 
// Found 10 items: 

for (WebElement element: allAccoElements){ 
System.out.println(element.getAttribute("id")); 
//Print 10 times with different id 
} 
+6

這是因爲您在'findElement'中使用了XPath選擇器,它以'/'開頭(它指向HTML的根,因此不適用於'element'的上下文)。 – p0deje 2012-04-09 09:12:06

+0

事實上,要在其他地方找到相應的項目,我們必須解決它(通過在xpath中的「//」之前添加點「。」): 謝謝p0deje您的建議! – 2012-04-09 09:28:49

+0

很高興幫助。隨意+1評論和回答這個問題,所以其他人可以找到解決方案。 – p0deje 2012-04-09 10:44:36

回答

3

感謝p0deje我們已經找到了答案:

要找到相應的其他項目裏面,我們必須要解決它(加入點前‘//’中的XPath「」) 。