如何处理空 element.and 的 NoSuchElementException 仍然执行下一行代码?

How to Handle NoSuchElementException for empty element.and still execute next line of code?

我正在尝试将动态网络 table 的文本获取到 excel sheet ,有时文本出现在列的行中,有时则不是..当文本出现时在 table 行中,我想获取该单元格的文本..使用 getText 方法,但是当文本不存在时我想写空文本并保持单元格空白..但它给出了 NoSuchElementException..如何处理那个..?任何帮助将不胜感激..提前致谢..

    String actualXpath_SL = beforeXpath_SL + j + afterXpath_SL;
    String SL = driver.findElements(By.xpath(actualXpath_SL)).getText()

    currentRow.createCell(0).setCellValue(SL);

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

  • 将代码放在 try 块中,并在 catch 块中处理 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检查返回列表是否为空。

List<WebElement> elements  = driver.findElements(By.xpath(actualXpath_1A));
String OneA = "";
if(!elements.isEmpty()){
    OneA = elements.get(0).getText();
} else {
    //Handle if no element present
}

第二种解决方案避免了异常,比等待异常更快。

你应该使用 .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 的 if 条件的逻辑。