Oualid L.
Oualid L.

Reputation: 11

Selenium get Element with label

i'm trying to get the texts (answers) next to the radiobuttons, to compare them with the correct answer.

Here is the html part:

<tbody>
 <tr>
    <td class="middle" width="15">
        <input name="multiple_choice_result" value="0" id="0" type="radio">
    </td>
    <td class="middle">
       <label for="0">FIRST ANSWER</label>  // This text
    </td>
 </tr>
 <tr>
    <td class="middle" width="15">
        <input name="multiple_choice_result" value="1" id="1" type="radio">
    </td>
    <td class="middle">
      <label for="1">SECOND ANSWER</label>  //This text
    </td>
 </tr>
 <tr>
    <td class="middle" width="15">
        <input name="multiple_choice_result" value="2" id="2" type="radio">
    </td>
    <td class="middle">
        <label for="2">THIRD ANSWER</label>  //This text
    </td>
 </tr>

</tbody>

Upvotes: 1

Views: 3013

Answers (1)

Shubham Jain
Shubham Jain

Reputation: 17593

Use below Xpath:-

//label[contains(.,'ANSWER')]

Note:- Above xpath will return 3 elements so I am using List

List<WebElement> allanswer = driver.findElements(By.xpath("//label[contains(.,'ANSWER')]"));
for(WebElement answer: allanswer){
        System.out.println(answer.getText());
}

If you want any particular answer then use:-

//label[contains(.,'FIRST ANSWER')]

Replace FIRST with SECOND OR THIRD according to your need

String answer =driver.findElement(By.xpath("//label[contains(.,'FIRST ANSWER')]")).getText();

Hope it will help you :)

Upvotes: 1

Related Questions