简体   繁体   English

如何在硒中打印列表数组的最后一个字符串值?

[英]How to print last string value of List Array in selenium?

There are multiple String element having same xpath.有多个具有相同 xpath 的 String 元素。 I have store elements in page object model using List<WebElement> mechanism.我使用List<WebElement>机制在页面对象模型中存储元素。 In my test case i want to print last string value of list.在我的测试用例中,我想打印列表的最后一个字符串值。

Below is the code of elements stored in repository.下面是存储在存储库中的元素的代码。

public Collection<WebElement> UpdatedMessageList(){
    Collection<WebElement> element=driver.findElements(By.xpath("//p[@class='msg-paragraph-panel msg-paragraph-msg ng-binding']"));
    return element;
}

Can anyone help me to print last string value from my test case?谁能帮我打印测试用例中的最后一个字符串值?

findElements returns a List , not just any old Collection , so you could use a positional get(int) : findElements返回一个List ,而不仅仅是任何旧的Collection ,因此您可以使用位置get(int)

public WebElement UpdatedMessageList(){
    List<WebElement> elements = 
        driver.findElements(By.xpath(
            "//p[@class='msg-paragraph-panel msg-paragraph-msg ng-binding']"));
    if (elements.isEmpty()) {
        return null; // Or throw some meaningful exception
    }
    return elements.get(elements.size() - 1);
}

I am pretty much sure above code will give you compile error, not sure if you are using Java 9 and something has changed.我非常确定上面的代码会给你编译错误,不确定你是否使用 Java 9 并且有些东西已经改变了。

Also, Don't use genertic collection class, findElements returns List of WebElements另外,不要使用泛型集合类, findElements返回List of WebElements

public WebElement UpdatedMessageList(){
    List<WebElement> element = driver.findElements(By.xpath("//p[@class='msg-paragraph-panel msg-paragraph-msg ng-binding']"));
    return element.get(element.size()-1);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM