2016-12-01 12 views
1

我使用Node.js selenium-webdriver,我有这个烦人的问题。我有这个登录功能填写了一些字段,然后尝试通过触发一个按钮点击登录到一个网站。我知道登录是否成功的方法是在点击按钮后等待某个元素。我想等待5秒钟,并根据来电者做出相应的响应。selenium-webdriver node.js:如何处理等待超时(异常似乎无法捕获)后丢失的元素

问题是,等待函数抛出一个异常,并使用try/catch,这没有帮助(异常未捕获,程序退出)。

这是我的代码:

var webdriver = require('selenium-webdriver'), 
    By = webdriver.By, 
    until = webdriver.until; 

var driver = new webdriver.Builder() 
    .forBrowser('chrome') 
    .build(); 

var timeout = 5000; 

function login(username, password, callback) { 
    driver.get('https://www.example.com/'); 

    driver.switchTo().frame(driver.findElement(By.css("iframe"))); 
    driver.findElement(By.name('userid')).sendKeys(username); 
    driver.findElement(By.name('password')).sendKeys(password); 
    driver.findElement(By.id('submit_btn')).click(); 

    driver.wait(until.elementLocated(By.className('indication-that-login-was-successful')), timeout).then(function(elm) { 
     callback(true); 
     driver.quit(); 
    }); 
} 

所以,如果登录不成功(例如,由于密码不正确),元素indication-that-login-was-successful绝不会出现(一件好事)。但在这种情况下,我不断收到

TimeoutError: Waiting for element to be located By(css selector, .indication-that-login-was-successful) Wait timed out after 5001ms 

理想我能赶上这个异常,并以虚假的回调并退出驱动程序:

try { 
    driver.wait(until.elementLocated(By.className('indication-that-login-was-successful')), timeout).then(function(elm) { 
     callback(true); 
     driver.quit(); 
    }); 
} catch (ex) { 
    callback(false); 
    driver.quit(); 
} 

然而如上所述,用try/catch块包装这件事没有按” t似乎有所帮助,这个例外从未被发现并且程序存在。

任何想法?

回答

2

你可以试试:

driver.wait(until.elementLocated(By.className('indication-th‌​at-login-was-success‌​ful')), 5000).then(function(elm) { 
     callback(true); 
     driver.quit(); 
    }).catch(function(ex) { 
     callback(false); 
     driver.quit(); 
    }); 
+0

喜灵,谢谢。你的回答非常好(它帮助我指出了正确的方向)。如果elementLocated函数返回的promise对象,我使用了catch函数。你可以编辑你的答案来使用它(这与我使用诺言API的问题更相关)。谢谢 driver.wait(until.elementLocated(By.className('indication-that-login-was-successful')),5000).then(function(elm){callback(true); driver.quit ); })。catch(function(ex){ callback(false); driver.quit(); }); – orcaman

+1

我很高兴它可以帮助你。我会根据你的建议更新答案 –

相关问题