Selenium RC:如何检查元素是否具有给定属性?

时间:2010-06-02 15:34:52

标签: php selenium attributes phpunit selenium-rc

我有一些带有onclick属性的按钮,有些则没有。{我想检查指定的元素是否具有onclick属性。我怎么能这样做?

getAttribute()返回属性值。如果没有,它会抛出RuntimeException并停止测试(即使我将它包装在try / catch块中)。

$onclickValue = $this->getAttribute("$locator@onclick"); //works when the attribute exists

4 个答案:

答案 0 :(得分:4)

使用getEval(),您可以执行javascript hasAttribute()功能。使用findElement(),您可以使用任何类型的定位器模式。

$hasAttribute = $this->getEval('this.browserbot.findElement("' . $locator . '").hasAttribute("onclick")');
if ($hasAttribute === 'true') {
    //attribute exists
}

请注意getEval()返回一个字符串,而不是布尔值。

答案 1 :(得分:2)

您可以先使用XPath //location/of/element[@onclick]

检查元素是否存在

答案 2 :(得分:0)

如果这不适用于Selenium RC,请原谅。在Selenium IDE中,可以使用

assertElementNotPresent

命令,(尽管名称)可以确定是否存在给定属性。它唯一的参数是一个元素定位器,可以是

形式

element-id@attribute

当然,只有当您知道哪些元素应该具有相关属性时,这才是合适的。如果没有,那么我猜你将不得不使用XPath表达式迭代元素集。

答案 3 :(得分:0)

抛出RuntimeException的原因是因为PHPUnit的selenium驱动程序的工作方式。

它将某些情况视为执行测试执行的stop()的错误。特别是,在这种情况下停止测试的代码如下:

protected function getString($command, array $arguments)
{
    try {
        $result = $this->doCommand($command, $arguments);
    }

    catch (RuntimeException $e) {
        $this->stop();

        throw $e;
    }

    return (strlen($result) > 3) ? substr($result, 3) : '';
}

我已经在https://github.com/sebastianbergmann/phpunit/issues/276

处开启了有关处理驱动程序错误的方法的问题

顺便说一句,在/usr/share/php/PHPUnit/Extensions/SeleniumTestCase/Driver.php的doCommand()和getString()中删除对stop()的调用将使你的代码能够捕获异常并处理它如您所愿。