2013-02-01 180 views
1

我有一張表,我試圖測試。其中一列是yes/no單選按鈕,當頁面被渲染時,隱藏在圖像下方,以便在選擇yes或no時有複選標記或X.獲取隱藏元素的屬性

選擇是時單選按鈕的屬性checked="true"

我如何使用Selenium2獲得該屬性,以便我可以對其進行比較或對其進行斷言?

我已經嘗試過以下,這隻會導致空指針錯誤。

private void verifyPOEligibleYesNull(String driverName) 
{ 
    int min = 1; 
    int max = 6; 
    JavascriptExecutor js = (JavascriptExecutor)driver; 
    StringBuilder stringBuilder = new StringBuilder(); 
    //Navigate to System Facing 
    driver = browser.getDriver(driverName); 
    driver.manage().window().maximize(); 
    driver.navigate().to("http://theURL"); 

    //Enter userName 
    WebElement userName = driver.findElement(By.id("username")); 
    userName.clear(); 
    userName.sendKeys(user); 

    //Enter Password 
    WebElement password = driver.findElement(By.id("pword")); 
    password.clear(); 
    password.sendKeys(pwd); 

    //Click Login 
    WebElement loginBtn = driver.findElement(By.xpath("/html/body/div/div/form/div[3]/div/input")); 
    loginBtn.click(); 
    try 
    { 
     Thread.sleep(5000); 
    } 
    catch (InterruptedException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    WebElement ivToPoBtn = driver.findElement(By.xpath("/html/body/div/div/div/ul/li/a/img")); 
    ivToPoBtn.click(); 
    try 
    { 
     Thread.sleep(5000); 
    } 
    catch (InterruptedException e) 
    { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    //Grab a random row and determine whether the PO Eligible is "Yes" 
    String rowNum = Integer.toString(rand.nextInt(max - min + 1) + min); 
    WebElement randomRow = driver.findElement(By.xpath("/html/body/div/div/div/div/form/div/div[2]/div/div[2]/div/div/div/div/div/div/div/table/tbody/tr["+rowNum+"]/td/div/div/input")); 
    String poEligibleChecked = randomRow.getAttribute("checked").toString(); 
    stringBuilder.append("var x = $(\""+poEligibleChecked+"\");"); 
    stringBuilder.append("return x.toString();"); 
    String res = (String) js.executeScript(stringBuilder.toString()); 
    System.out.println(res);  
} 

我甚至試過這是從WebDriver FAQ建議如下:

WebElement randomRow = driver.findElement(By.xpath("/html/body/div/div/div/div/form/div/div[2]/div/div[2]/div/div/div/div/div/div/div/table/tbody/tr["+rowNum+"]/td/div/div/input")); 
    String poEligibleChecked = randomRow.getAttribute("checked"); 
    String element = js.executeScript("return arguments[0].getText();", poEligibleChecked).toString(); 
    System.out.println(element); 

類似的空指針異常錯誤。

回答

2

你的代碼沒有意義。爲了得到一種無形要素的checked屬性,只需使用element.getAttribute()

final String scriptGetChecked = "return arguments[0].getAttribute('checked')"; 

WebElement randomRow = driver.findElement(By.whatever("something")); 
String checkedState = (String) js.executeScript(scriptGetChecked, randomRow); 
+0

我仍然得到了'NullPointerException'當我試圖你有什麼上面。我得到的例外是最後一個,我運行'JavaScriptExecutor' – DarthOpto

+1

這是行得通的,謝謝你的幫助。 – DarthOpto