2010-06-02 44 views
2

我有一些onclick屬性的按鈕,有些則沒有。我想檢查指定的元素是否具有onclick屬性。我怎樣才能做到這一點?Selenium RC:如何檢查一個元素是否有給定的屬性?

getAttribute()返回屬性值,當它有一個。當它沒有時,它會拋出一個RuntimeException並停止測試(即使我將它包裝在try/catch塊中)。

$onclickValue = $this->getAttribute("[email protected]"); //works when the attribute exists 

回答

4

使用getEval(),您可以執行JavaScript hasAttribute()功能。使用findElement(),將允許您使用任何類型的定位器模式。

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

請注意getEval()返回一個字符串,而不是布爾值。

2

你可以先檢查元素存在使用XPath //location/of/element[@onclick]

0

請原諒,如果這不適用於Selenium RC。在硒IDE,一個可以使用

assertElementNotPresent

命令,該命令(儘管名稱)可確定給定的屬性是否存在。這只是參數是元素定位器,其形式可以是

[email protected]

當然,只有當您知道哪些元素應該具有該屬性時才適用。如果不是,那麼我猜你必須使用XPath表達式遍歷元素集。

+0

謝謝你的評論。我一直在爲Selenium IDE尋找這個例子,而不是RC,因此它有所幫助。 – 2012-10-25 15:53:49

0

拋出RuntimeException的原因是因爲PHPUnit的硒驅動程序的工作原理。

它將某些情況視爲執行測試執行的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

打開關於駕駛員的錯誤處理這樣的問題BTW,去除叫停()在/usr/share/php/PHPUnit/Extensions/SeleniumTestCase/Driver.php的doCommand()和getString()中將使您的代碼能夠捕獲異常並按照您的偏好進行處理。

相關問題