我正在尝试将动态Web表的文本转换为excel工作表,有时文本出现在列的行中,有时则不是。.当文本出现在表行中时,我想获取该单元格的文本。 .using getText方法,但是当不存在Text时,我想写空文本并使单元格保持空白..但是它给NoSuchElementException ..如何处理它。任何帮助将不胜感激..预先感谢..
String actualXpath_SL = beforeXpath_SL + j + afterXpath_SL;
String SL = driver.findElements(By.xpath(actualXpath_SL)).getText()
currentRow.createCell(0).setCellValue(SL);
答案 0 :(得分:2)
要在硒找不到元素时继续执行程序,您可以做两件事。
(0, 'dogdog')
(1, 'aaaoa')
。 NoSuchElementException
或,您可以使用String OneA = "";
try{
//find element
OneA = driver.findElement(By.xpath(actualXpath_1A)).getText();
}catch (NoSuchElementException e){
//stacktrace and other code after catching the exception
e.printStackTrace();
}
并检查返回的列表是否为空。
findElements
第二种解决方案避免了异常,它比等待异常更快。
答案 1 :(得分:0)
您应该使用.size()>0
而不是isEmpty()
String actualXpath_2S = beforeXpath_2S + j + afterXpath_2S;
List<WebElement> eight = driver.findElements(By.xpath(actualXpath_2S));
String TwoS="";
if(eight.size()>0){
TwoS = eight.get(0).getText();
}
如果条件是使用isEmpty
,则必须更新所有逻辑。