How to locate a list element (Selenium)?

Buras picture Buras · Apr 6, 2013 · Viewed 11.6k times · Source

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

Answer

fredrik picture fredrik · Apr 6, 2013

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