1

我有一张我正在尝试测试的桌子。其中一列是是/否单选按钮,当页面呈现时隐藏在图像下方,以便在选择是或否时有一个复选标记或 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);

与类似的空指针异常错误。

4

1 回答 1

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);
于 2013-02-02T07:43:38.487 回答