2015-03-02 67 views
1

我試圖測試ROUND TRIP是否被選中。我可以看到ROUND TRIP被選中,但我仍然得到輸出爲false爲什麼?isSelected()方法在硒代碼中返回false

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.firefox.FirefoxDriver; 

public class IsSelected { 
public static void main(String[] args) { 
    WebDriver f= new FirefoxDriver(); 
    f.get("http://www.makemytrip.com/"); 
    WebElement e = f.findElement(By.id("round_trip_button1")); 
    System.out.println(e.isSelected()); 
    System.out.println(e.getText()); 
    System.out.println(e.isDisplayed()); 
    System.out.println(e.isEnabled()); 

    } 

}

回答

1

isSelected()適用於輸入 元素如複選框,在選項中進行選擇單選按鈕。

但在你的情況下,它通過'a'(錨文本)實現,所以默認isSelected()將不起作用。

對於您的情況我檢查了'a'屬性,您可以通過檢查類值'active'來輕鬆地自定義實現isSelected()方法。 選擇了round_trip_button1 id時,其類包含字符串'active',而其他大小寫'active'缺失。

3

round_trip_button1 ID的元素是a元素,但你需要一個實際的inputradio類型,而不是:

f.findElement(By.cssSelector("a#round_trip_button1 input[type=radio]")); 

UPD:遵循@aberry答案 - 你需要檢查a標記以獲得active類。定義一個function that would check for an element to have a class

public static bool hasClass(WebElement el, string className) { 
    return el.getAttribute("class").split(' ').contains(className); 
} 

並使用它:

hasClass(f.findElement(By.id("round_trip_button1")), 'active'); 
+0

仍然顯示相同的假 – 2015-03-02 09:01:21

+0

@amolsaxena請參閱更新。 – alecxe 2015-03-02 14:18:00