我从 HTML 表中获取了一些值。我可以打印这些值,但无法找出按字母顺序对它们进行排序的方法。
我使用的代码 -
List<WebElement> lst = driver.findElements(By.xpath(".//*[@class='user-questions lines']/tbody/tr/td[2]"));
for(WebElement s : lst) {
System.out.println(s.getText()); //This line prints the value
String[] ss = new String[lst.size()];
int i=0;
if(s.getText() != null) {
ss[i]=s.getText();
System.out.println(ss[1]); // But here i am getting null
}
i++;
}
首先,我尝试使用Collections.sort(lst)
对其进行排序,但收到错误消息:
Bound mismatch: The generic method sort(List) of type Collections is not applicable for the arguments (List).
然后我尝试将字符串值放入字符串数组中,然后对其进行排序,但是当我尝试将值放入字符串数组中时,我得到空值
最佳答案
今天我陷入了同样的困境,发现这个问题早在今年年初就被问到了。当我尝试给出的解决方案时,我得到了 NullPointerException。
我编写了一段小代码,现在我可以根据自然字母顺序缩短网络元素。这是代码-
//Here storing the WebElements in the List
List<WebElement> lst = driver.findElements(By.xpath("WebElement XPath"));
//Here creating a String array
String[] str = new String[lst.size()];
for (int i = 0 ; i<str.length ; i++){
str[i] = driver.findElements(By.xpath("WebElement XPath")).get(i).getText();
}//for
Arrays.sort(str);
for(String strr: str){
System.out.println(strr);
}
driver_1.close();
driver_1.quit();
}//try
catch(Exception e){
e.printStackTrace();
driver.close();
driver.quit();
}//catch
首先,我将网络元素存储在列表中。然后我创建了一个用于排序的字符串数组。在第一个 for 循环中,我存储了从网站获得的字符串。之后我使用 Arrays.sort 方法对它们进行排序
在高级 for 循环中,我正在打印输出。
据我所知,这个问题已经很老了,如果在这段时间您得到了更好的答案,请分享。
关于java - 如何筛选其中包含 WebElement 的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28040120/