Kang-Lin Cheng
Kang-Lin Cheng

Reputation: 11

How to get the text for radio buttons using Selenium Java

I have the following HTML code:

<form action=""><input type="radio" id="r1" name="city" value="la">Los Angeles</br><input type="radio" id="r2" name="city" value="sf">San Francisco</br>input type="radio" id="r3" name="city" value="ny">New York</br><input type="radio" id="r4" name="city" value="chicago">Chicago</br></form>

In Selenium WebDriver using Java, I am trying to capture the text of each radio button (so "Los Angeles", "San Francisco", etc.) Here is my code:

public static void radioTest(WebDriver driver){
List<WebElement> radios = driver.findElements(By.name("city"));
for(int i = 0; i<radios.size(); i++){
    radios.get(i).click(); 
    System.out.println(radios.get(i).getAttribute("value"));

}

}

The problem here is that it is returning "la", "sf", etc., when I want the actual text ("Los Angeles", "San Francisco", etc.) Can anyone please offer any advice? Thank you.

Upvotes: 1

Views: 1683

Answers (4)

iamsankalp89
iamsankalp89

Reputation: 4739

it returns "la", "sf", etc. beacuse you are extracting value attribute using getAttribute() method, for the text you have to use getText() method.

Try this code and let me konw any issue occured:

public static void radioTest(WebDriver driver){
List<WebElement> radios = driver.findElements(By.name("city"));
for(int i = 0; i<radios.size(); i++){
    radios.get(i).click(); 
    String cityName=radios.get(i).getText();
    System.out.println("Name of city: "+cityName);
}

}

Upvotes: 0

undetected Selenium
undetected Selenium

Reputation: 193298

To capture the text of each radio button, you can use the following code block :

List<WebElement> my_cities = driver.findElements(By.xpath("//input[@name='city' and @type='radio']"));
for (WebElement city:my_cities)
    System.out.println("City name is : " + city.getAttribute("innerHTML")); 

Upvotes: 0

Shoaib Akhtar
Shoaib Akhtar

Reputation: 1403

Check by getText() method instead of value attribute and check

for(int i = 0; i<radios.size(); i++){
    radios.get(i).click(); 
    System.out.println(radios.get(i).getText());

}

Upvotes: 1

L.H
L.H

Reputation: 81

You can install a developer tools on chrome or safari to check the properties and their run time values. In chrome you can open developer tools, go to 'Elements' tab, click on the element of interest. It will show the properties of element in the right side. There yo can see which property/attribute you are interested in and get the value accordingly using code.

Upvotes: 0

Related Questions