Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 present. I would like to create a method that would pass if the element is not present.

I am using selenium webdriver and java. I know I can retrieve attributes by using getSingleElement(XXX).getAttribute(XXX). I'm just not sure how to verify that an attribute does not exist, and for the test to pass when it doesn't exist (fail if it does exist).

When the radio button is checked

<input id="ctl00_cphMainContent_ctl00_iq1_response_0" type="radio" name="ctl00$cphMainContent$ctl00$iq1$response" value="1" checked="checked">  

When the radio button is not checked

<input id="ctl00_cphMainContent_ctl00_iq1_response_0" type="radio" name="ctl00$cphMainContent$ctl00$iq1$response" value="1"> 

I want the test to pass when the checked attribute is not present

like image 582
TestRaptor Avatar asked Dec 17 '13 21:12

TestRaptor


People also ask

What is the method used to check the Webelement is present?

isDisplayed() is the method used to verify a presence of a web element within the webpage. The method returns a “true” value if the specified web element is present on the web page and a “false” value if the web element is not present on the web page.

How do you check if a element is present in the list in Selenium?

We can verify if an element is present using Selenium. This can be determined with the help of findElements() method. It returns the list of elements matching the locator we passed as an argument to that method. In case there is no matching element, an empty list [having size = 0] will be returned.


2 Answers

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 
like image 121
Yi Zeng Avatar answered Oct 04 '22 13:10

Yi Zeng


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

like image 39
mehmetg Avatar answered Oct 04 '22 13:10

mehmetg