2016-09-17 101 views
0

使用PHP Webdriver捕獲異常的正確方法是什麼?我有這樣的事情:Selenium PHP Webdriver - 沒有捕捉到異常?

try { 
    // Throws a NoSuchElementException if id doesn't exist 
    $driver->findElement(WebDriverBy::id('loggedIn')); 
    return TRUE; 
} 
catch (NoSuchElementException $e) { 
    // id='loggedIn' doesn't exist 
    return FAlSE; 
} 
catch (Exception $e) 
{ 
    // Unknown exception 
    return FALSE; 
} 

然而,當我到達一個頁面,沒有找到與id我在尋找的元素,我得到以下錯誤:

Uncaught Facebook\WebDriver\Exception\NoSuchElementException: Unable to locate element: #loggedIn

我我不確定爲什麼我的代碼被封裝在try-catch塊中。

回答

1

我會建議你避免try..catch並檢查元素是否在頁面上沒有得到一個例外,只是嘗試使用findElements而不是如果沒有找到這將返回要麼匹配定位器或空數組所有元素的數組,所以你只是需要檢查數組數來確定該元素的存在與否,如下: -

if (count($driver->findElements(WebDriverBy::id("loggedIn"))) > 0) 
{ 
    return TRUE; 
}else 
{ 
    return FALSE; 
} 
+0

這對'findElement'可能的解決方法,但它不回答爲什麼我無法捕捉異常。 – StackOverflowNewbie

+0

好吧,確保你抓住了正確的'NoSuchElementException'。首先驗證是否爲'NoSuchElementException'導入了正確的類? –

+0

並確保異常拋出此代碼或不在'try..catch'塊內的其他代碼? –

0

這個工作對我來說,希望這可以幫助別人

try { 
    ... 
} catch (Exception\NoSuchElementException) { 
    ... 
}