在Selenium Java+TestNG框架中元素未显示后继续执行后续步骤
问题分析
你的脚本在元素不存在时停止执行,核心原因有两个:
- 第一个检查流程中,
assert processHeader.isDisplayed()抛出的AssertionError不在当前catch的捕获范围内,异常未被处理导致中断。 - 第二个检查流程中,
driver.findElement操作放在了try块外部,元素不存在时直接抛出NoSuchElementException,没有被捕获就会终止脚本。
修正后的代码
//Click Bautowatch WebElement bautoWatch = driver.findElement(By.xpath("//span[contains(text(),'Bautowatch')]")); bautoWatch.click(); Thread.sleep(1000); //Click Bautowatch Process WebElement bautoProcess = driver.findElement(By.xpath("//span[contains(text(),'Process')]")); bautoProcess.click(); Thread.sleep(1000); //Check Process header is displayed to confirm Bautowatch Process page is loaded try { WebElement processHeader = driver.findElement(By.xpath("(//div[contains(text(),'Processnew')])[1]")); assert processHeader.isDisplayed(); Thread.sleep(1000); System.out.println("Bautowatch Process - Pass"); Properties.screenshotMethod(driver, "Bautowatch Process - Pass"); } catch (NoSuchElementException | AssertionError e) { System.out.println("Bautowatch Process - Fail"); Properties.screenshotMethod(driver, "Bautowatch Process - Fail"); } //Click Bautowatch Connector WebElement bautoConnector = driver.findElement(By.xpath("(//span[contains(text(),'Connector')])[1]")); bautoConnector.click(); Thread.sleep(1000); //Check Connector header is displayed to confirm Bautowatch Connector page is loaded try { WebElement connectorHeader = driver.findElement(By.xpath("(//div[contains(text(),'Connector')])[1]")); assert connectorHeader.isDisplayed(); Thread.sleep(1000); System.out.println("Bautowatch Connector - Pass"); Properties.screenshotMethod(driver,"Bautowatch Connector - Pass"); } catch (NoSuchElementException | AssertionError e){ System.out.println("Bautowatch Connector - Fail"); Properties.screenshotMethod(driver,"Bautowatch Connector - Fail"); }
关键修改点
- 第一个检查块:
catch同时捕获NoSuchElementException(元素不存在)和AssertionError(元素存在但未显示),确保两种失败场景都能被处理,脚本继续执行。 - 第二个检查块:将
driver.findElement移到try块内部,这样元素不存在时抛出的异常能被catch捕获,避免脚本中断。
额外优化建议
- 尽量替换
Thread.sleep为WebDriver的显式等待(WebDriverWait),例如等待元素可点击/可见,这样能让脚本更稳定,减少不必要的等待时间。示例:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement bautoWatch = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//span[contains(text(),'Bautowatch')]")));
内容的提问来源于stack exchange,提问作者Vignesh Kps
相关产品推荐
相关产品推荐

