java 如何定位列表元素(Selenium)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15854883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 21:03:31  来源:igfitidea点击:

How to locate a list element (Selenium)?

javalistxpathseleniumnosuchelementexception

提问by Buras

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

但是,我得到了: NoSuchElementException... 我可以使用 cssSelector 但我没有 ul 的 id

回答by fredrik

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

我认为 XPath 应该是"//ul/li[1]". 在 selenium 中,第一项是 1,而不是 0。看这里

回答by IndoKnight

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()

回答by Dimitre Novatchev

(//ul/li)[1]

This selects the first in the XML document lielement that is a child of a ulelement.

这将选择 XML 文档li元素中作为ul元素子元素的第一个元素

Do note that the expression:

请注意表达式

//ul/li[1]

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

选择li作为ul其父元素的第一个子元素的任何元素。因此,该表达式通常可以选择多个元素。

回答by djangofan

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() );
  }
}