Selenium RC: How to check if an element has a give

2019-07-21 17:53发布

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

4条回答
We Are One
2楼-- · 2019-07-21 18:00

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.

查看更多
The star\"
3楼-- · 2019-07-21 18:04

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.

查看更多
来,给爷笑一个
4楼-- · 2019-07-21 18:18

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.

查看更多
Summer. ? 凉城
5楼-- · 2019-07-21 18:19

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

查看更多
登录 后发表回答