2016-09-17 130 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) { 
    ... 
}