Selenium PHP Webdriver - 没有捕获异常?

时间:2016-09-17 08:21:52

标签: php selenium selenium-webdriver

使用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   找到元素:#loggedIn

我不确定为什么我的代码包含在try-catch块中。

3 个答案:

答案 0 :(得分:2)

我建议你避免使用try..catch并检查该元素是否在页面上而不会出现异常,只需尝试使用findElements代替将返回所有具有匹配定位符的元素的数组或为空数组如果找不到任何内容,那么你需要检查数组计数以确定该元素是否存在,如下所示: -

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

答案 1 :(得分:1)

这对我有用,希望这有助于某人

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

答案 2 :(得分:0)

我不确定为何异常和特定异常都不起作用,但是:

捕获(WebDriverException $ e)

为我工作)