Java 如何在短名单中包含WebElement
我从HTML表中获得了一些值。我可以打印这些值,但无法找到按字母顺序排序的方法 我使用的代码-Java 如何在短名单中包含WebElement,java,arrays,sorting,arraylist,selenium-webdriver,Java,Arrays,Sorting,Arraylist,Selenium Webdriver,我从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 va
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++;
}
List lst=driver.findElements(By.xpath(“./*[@class='user-questions-lines']]/tbody/tr/td[2]”);
for(WebElement s:lst){
System.out.println(s.getText());//此行打印值
字符串[]ss=新字符串[lst.size()];
int i=0;
如果(s.getText()!=null){
ss[i]=s.getText();
System.out.println(ss[1]);//但是这里我得到了null
}
i++;
}
首先,我尝试使用集合对其进行排序。排序(lst),但收到一条错误消息:
绑定不匹配:类型集合的泛型方法排序(列表)不适用于参数(列表)
然后我尝试将字符串值放入字符串数组,然后对其进行排序,但在这里,当我尝试将值放入字符串数组时,得到的值为空值您在
System.out.println(ss[1])处得到的值为空代码>
因为:
ss[i]=s.getText()
总是放在ss[0]
中,因为:
在ifint i=0之前代码>。
所以ss[1]
总是空的
要解决这个问题,请输入int i=0代码>在(WebElement s:lst)的之前
在foreach循环外部声明i
。和sysoutss[i]
。在第一次循环执行时,显然ss[1]
将null
另一种方法是:
List<WebElement> lst = driver.findElements(By.xpath(".//*[@class='user-questions lines']/tbody/tr/td[2]"));
String[] str = new String[lst.size()];
int i = 0;
for (WebElement ele : lst) {
if(ele.getText()!=null)
str[i] = ele.getText();
i++;
}
Arrays.sort(str); // to sort the array of strings
List lst=driver.findElements(By.xpath(“./*[@class='user-questions-lines']]/tbody/tr/td[2]”);
字符串[]str=新字符串[lst.size()];
int i=0;
for(WebElement ele:lst){
if(ele.getText()!=null)
str[i]=ele.getText();
i++;
}
数组。排序(str);//对字符串数组进行排序
今天,我陷入了同样的困境,发现这个问题早在今年年初就被问到了。当我尝试给出的解决方案时,我得到了一个NullPointerException
我写了一个小代码,现在我能够按照自然的字母顺序缩短Web元素。这是密码-
//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
//此处存储列表中的WebElements
List lst=driver.findElements(By.xpath(“WebElement xpath”);
//这里创建一个字符串数组
字符串[]str=新字符串[lst.size()];
对于(int i=0;iAs WebElement未实现Comparable
接口,您需要调用Collections.sort(List,Comparator)
方法。在Comparator中,您需要定义如何对WebElement进行排序。您的代码似乎缺少开头try{
用于try-catch块。顺便说一句:我会使用缩进而不是//for
,//try
和//catch
注释在右括号中。