Selenium RC: How to check if an element has a given attribute?

此生再无相见时 提交于 2019-12-24 04:13:09

问题


I have some buttons with an onclick attribute and some that don't. I want to check if the specified element has the onclick attribute. How can I do this?

getAttribute() returns the attribute value when it has one. When it doesn't, it throws a RuntimeException and stops the test (even when I wrap it in a try/catch block).

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

回答1:


By using getEval(), you can execute the javascript hasAttribute() function. Using findElement(), will allow you to work with any type of locator pattern.

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

Note that getEval() returns a string, not a boolean.




回答2:


You could first check if the element is present using XPath //location/of/element[@onclick]




回答3:


Please excuse me if this does not apply to Selenium RC. In Selenium IDE, one can use the

assertElementNotPresent

command, which (despite the name) can determine whether a given attribute is present. It's only parameter is an element locator that can be of the form

element-id@attribute.

Of course this will only be appropriate if you know which elements should have the attribute in question. If not then I guess you'll have to iterate through element sets using XPath expressions.




回答4:


The reason why a RuntimeException is thrown is because the way PHPUnit's selenium driver works.

It considers certain situations as errors that perform a stop() of the test execution. In particular, the code that stops the test in that situation is the following:

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) : '';
}

I already opened an issue regarding this way of handling errors in the driver at https://github.com/sebastianbergmann/phpunit/issues/276

BTW, removing the calls to stop() in both doCommand() and getString() of /usr/share/php/PHPUnit/Extensions/SeleniumTestCase/Driver.php will make your code able of catching the exception and handling it as you prefer.



来源:https://stackoverflow.com/questions/2959188/selenium-rc-how-to-check-if-an-element-has-a-given-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!