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似乎有所幫助,這個例外從未被發現並且程序存在。
任何想法?
喜靈,謝謝。你的回答非常好(它幫助我指出了正確的方向)。如果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
我很高興它可以幫助你。我會根據你的建議更新答案 –