Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Selenium PHP Webdriver-不捕获异常?_Php_Selenium_Selenium Webdriver - Fatal编程技术网

Selenium PHP Webdriver-不捕获异常?

Selenium PHP Webdriver-不捕获异常?,php,selenium,selenium-webdriver,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

使用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为
id
的元素时,我会得到以下错误:

未捕获的Facebook\WebDriver\Exception\NoTouchElementException:无法 要定位元素:#loggedIn


我不知道为什么,因为我的代码被包装在一个try-catch块中

我建议您避免使用
try..catch
并检查元素是否在页面上而不会出现异常,只需尝试使用
findelelements
,它将返回所有元素的数组,如果没有找到匹配的定位器,则返回空数组,因此,只需检查数组计数即可确定元素是否存在,如下所示:-

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

这对我有用,希望这对别人有帮助

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

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

捕获(WebDriverException$e)


(对我有效)

这是
findElement
的一个可能的解决方法,但它不能回答我无法捕获异常的原因。好的,请确保捕获的是正确的
NoTouchElementException
。首先验证您是否为
NoTouchElementException
?导入了正确的类,并确保从该代码或不在
try..catch
块中的某些其他代码引发异常??