How to verify an attribute is present in an element using Selenium WebDriver?

前端 未结 6 2088
旧巷少年郎
旧巷少年郎 2020-12-31 02:14

I have many radio buttons on my screen. When a radio button is selected, it has an attribute of checked. When the radio button is not selected, the checked attribute is not

相关标签:
6条回答
  • 2020-12-31 02:21

    Look here:

    getAttribute(java.lang.String name)

    Returns: The attribute's current value or null if the value is not set.

    Use whatever test framework you're using to assert that the value is null

    Assert.IsNull(getSingleElement(XXX).getAttribute("checked"));

    0 讨论(0)
  • 2020-12-31 02:24

    Checkboxes can tricky sometimes, because the attribute checked may not be followed by an attribute value.

    If you're only concerned with the presence of the attribute, a simple check would look like this:

     boolean hasAttr_css = driver.findElementsByCssSelector("#input_id[checked]").isEmpty();
    
    0 讨论(0)
  • 2020-12-31 02:27

    You can create a method to handle it properly. Note this following is in C#/Java mixed style, you need to tweak a bit to compile.

    private boolean isAttribtuePresent(WebElement element, String attribute) {
        Boolean result = false;
        try {
            String value = element.getAttribute(attribute);
            if (value != null){
                result = true;
            }
        } catch (Exception e) {}
    
        return result;
    }
    

    How to use it:

    WebElement input = driver.findElement(By.cssSelector("input[name*='response']"));
    Boolean checked = isAttribtuePresent(input, "checked");
    // do your assertion here
    
    0 讨论(0)
  • 2020-12-31 02:28
    try { 
    if (webdriver.findElement(By.identificationMethod(value)).getAttribute(value) != null) {
           passed = false;
        }
    } catch (Exception e) {
        passed = true;
    }
    

    Was the sort of solution I used when I needed to check for element presence, however it must be noted that NullPointer errors were not caught by the NoSuchElement exception.

    0 讨论(0)
  • 2020-12-31 02:37

    Unfortunately the accepted answer is not valid in the case reported. For some reason for Cr and FF non-existing attributes return empty string rather than null. Issue linked: https://github.com/SeleniumHQ/selenium/issues/2525

    0 讨论(0)
  • 2020-12-31 02:42

    For asserting radio button is selected

    Assert.assertTrue(element.isSelected());
    

    For asserting radio button is not selected

    Assert.assertFalse(element.isSelected());
    

    For asserting an attribute is present in element

    Assert.assertEquals(element.getAttribute(attributeName), expectedAttributeValue);
    
    0 讨论(0)
提交回复
热议问题