2

I have the following list:

<ul>
<li> item1 is red
</li>
<li> item1 is blue 
</li>
<li> item1 is white  
</li>
</ul>

I tried the following to print the first item:

String item = driver.findElement(By.xpath("//ul//li[0]")).getText();
        System.out.println(item);

However, I got: NoSuchElementException... I could use a cssSelector but I do not have the id for the ul

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Buras
  • 3,069
  • 28
  • 79
  • 126

4 Answers4

7

I think that the XPath should be "//ul/li[1]". In selenium the first item is 1, not 0. Look here

fredrik
  • 6,483
  • 3
  • 35
  • 45
2

I know this is not as efficient as the other answer but I think it gives you the result.

WebElement element = (WebElement) ((JavascriptExecutor)driver).executeScript("return $('li').first()");

String item = element.getText()
Pavel Janicek
  • 14,128
  • 14
  • 53
  • 77
IndoKnight
  • 1,846
  • 1
  • 21
  • 29
  • 1
    Not going to downvote this because it will work, but you are playing a dangerous game: you are assuming that jQuery is loaded. jQuery is not a standard. – Arran Apr 07 '13 at 10:47
2
(//ul/li)[1]

This selects the first in the XML document li element that is a child of a ul element.

Do note that the expression:

//ul/li[1]

selects any li element that is the first child of its ul parent. Thus this expression in general may select more than one element.

Dimitre Novatchev
  • 240,661
  • 26
  • 293
  • 431
1

Here is how you do it:

List<WebElement> items = driver.findElements(By.cssSelector("ul li"));
if ( items.size() > 0 ) {
  for ( WebElement we: items ) {
   System.out.println( we.getText() );
  }
}
djangofan
  • 28,471
  • 61
  • 196
  • 289