Home > Software design >  C# selenium find an element by text then click on checkbox
C# selenium find an element by text then click on checkbox

Time:08-30

I want to search for example (UK) then click on checkbox that is in the same row

HTML (but tr can increase or decrease)

<tr >
    <td >US</td>
    <td >United States</td>
    <td  style="padding: 0;">
        <input type="checkbox" >
    </td>
</tr>
<tr >
    <td >UK</td>
    <td >United Kingdom</td>
    <td  style="padding: 0;">
        <input type="checkbox" >
    </td>
</tr>
<tr >
    <td >IN</td>
    <td >India</td>
    <td  style="padding: 0;">
        <input type="checkbox" >
    </td>
</tr>

CodePudding user response:

You can find the parent tr element based on child td containing the desired text and then find the child input element as following:

//tr[.//td[contains(.,'UK')]]//input

The entire Selenium command finding and clicking this element could be

driver.FindElement(By.XPath("//tr[.//td[contains(.,'UK')]]//input")).Click();

CodePudding user response:

solved by

IList<IWebElement> tableRow = tableElement.FindElements(By.TagName("tr"));
IList<IWebElement> rowTD;
if (tableRow.Count > 0)
{
    foreach (IWebElement row in tableRow)
    {
        rowTD = row.FindElements(By.TagName("td"));
        if (rowTD[0].Text.Equals("UK"))
            rowTD[2].Click();
    }
}
  • Related