如何处理空元素的NoSuchElementException并仍然执行下一行代码?

时间:2019-05-05 12:48:47

标签: java selenium nosuchelementexception

我正在尝试将动态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);

2 个答案:

答案 0 :(得分:2)

要在硒找不到元素时继续执行程序,您可以做两件事。

  • 将代码放入try块中,并在catch块中处理(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,则必须更新所有逻辑。