Java Selenium中使用等待机制捕获页面标题的异常问题
问题分析:Java Selenium等待标题时反向用例抛出TimeOutException
我在Java版Selenium中使用等待机制捕获页面标题,正向测试用例(传入标题值为“Log In”)运行正常,但反向测试用例(传入标题值为“Log in”)时,else代码块未执行,直接抛出TimeOutException,不清楚原因。相关代码如下:
public class WaitForTitleURL { static WebDriver driver; public static void main(String[] args) { // TODO Auto-generated method stub driver = new ChromeDriver(); driver.get("https://classic.crmpro.com/"); Thread.sleep(5000); By forgotPwd = By.xpath("//a[text()='Forgot Password?']"); driver.findElement(forgotPwd).click(); String title = waitForTitleAndCapture("Log in", 5); System.out.println(title); } public static String waitForTitleAndCapture(String value, int timeOut) { WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOut)); if(wait.until(ExpectedConditions.titleContains(value))) { String title = driver.getTitle(); return title; }else { System.out.println("Title is not present within the given timeout: " + timeOut); return null; } } }
原因解析
WebDriverWait.until()方法的设计逻辑是:
- 如果在超时时间内满足传入的条件,返回条件的结果(这里是boolean值true)
- 如果超时后仍未满足条件,直接抛出
TimeOutException,不会返回false,因此你的else分支永远不会被执行,程序会直接进入异常流程。
解决方案
通过try-catch块捕获超时异常,实现“存在则返回标题,不存在则执行异常逻辑”的需求,修改后的waitForTitleAndCapture方法如下:
public static String waitForTitleAndCapture(String value, int timeOut) { WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeOut)); try { // 等待标题包含指定值,超时则抛出异常 if(wait.until(ExpectedConditions.titleContains(value))) { return driver.getTitle(); } } catch (TimeoutException e) { // 捕获超时异常,执行标题不存在的逻辑 System.out.println("Title is not present within the given timeout: " + timeOut); } return null; }
修改说明
- 将等待逻辑放入
try块,条件满足时正常返回页面标题 - 捕获
TimeoutException,此时说明标题未在指定时间内匹配,执行提示逻辑并返回null
内容的提问来源于stack exchange,提问作者GAmeya
相关产品推荐
相关产品推荐

