selenium-webdriver

How to get the text inside span data-role and select matching checkbox using Selenium


I have the following:

Relevant HTML

I have a string I am trying to match. So I want to got through all the checkboxes (=173) and search for the one who has text = GAF. I then want to be able to check the checkbox (called span class="gj-icon")

So far I have the following which returns all the checkboxes.

IReadOnlyCollection<IWebElement> items = (IReadOnlyCollection<IWebElement>)driver.FindElements(By.XPath("//*[@data-role='checkbox']"));
foreach (IWebElement item in items)
{
    //if item.text = "GAF"
    //then click() the checkbox for GAF
}

How do I search through all the items to find the matching name GAF and then check its matching checkbox? The name I am searching for can change, it won't always be GAF, it can be one of the other 173 checkbox names.


Solution

  • You didn't post the HTML as text so I can't test the locator but this should work or at least be close enough that you can adjust.

    The easiest way to handle a situation like this is to build a dynamic XPath that contains the desired text, e.g. "GAF", and then gets you to the desired element. I would put this into a method that takes care of setting this checkbox and then pass in the desired value, e.g. "GAF".

    The method would look like,

    public void SetSomething(string something)
    {
        new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(By.XPath($"//li[.//span[text()='{something}']]//span[@class='gj-icon']"))).Click();
    }
    

    Change the method name to whatever the "GAF" checkbox represents, e.g. airport code, whatever.

    Then call it like

    SetSomething("GAF");
    

    Now you can pass it whatever value you want. If you want more control over the intended values, you could set up an enum and then pass that enum into the method to prevent hard-coded string typos, etc.