0

I have a form that uses Selenium to go to a page and automate tasks for a user. The only part of the page that changes is a CheckBoxList, and I've been trying to extract the labels from it and mirror them to my form's CheckedListBox so users can make the selection there without seeing the page.

So far I have this:

        IList<IWebElement> vehicleGroups = Builder.Driver.FindElements(By.ClassName("vehGrp"));
        String[] vehicleText = new String[vehicleGroups.Count];
        int i = 0;
        foreach (IWebElement element in vehicleGroups)
        {
            vehicleText[i++] = element.Text;
            vehicleGroupList.Items.Add(element.Text);
        }

Which works as far as getting the correct number of elements and populating the form, but all of the labels in vehicleText are blank (or just a space.)

An example of the HTML for one of the labels is

    <label><input type="checkbox" name="searchQuery.vehicleGroups[0].isSelected" value="on" class="vehGrp">&nbsp;abcd/efgh ijkl mn (opqrst)</label>

Did I miss something or is the " " messing with the label text? The "abcd/efgh ijkl mn (opqrst)" is what I need but it and the potential number of elements can change daily.

Sam Basso
  • 127
  • 1
  • 8

1 Answers1

0

vehicleGroups are the <input> elements, not the <label>s that surround them - and these have no text. This is expected behavior.

You need to get the surrounding <label> element, for example using a method like this: https://stackoverflow.com/a/12194481/7866667

var vehicleGroupInputElements = driver.FindElements(By.ClassName("vehGrp"));
var vehicleGroupNames = vehicleGroupInputElements
    .Select(e => e.FindElement(By.XPath("..")))
    .Select(e => e.Text)
    .ToArray();
j4nw
  • 2,227
  • 11
  • 26
  • Works. Had to change e to f and change some syntax but final result is: var vehicleGroupInputElements = Builder.Driver.FindElements(By.ClassName("vehGrp")); var vehicleGroupNames = vehicleGroupInputElements.Select(f => f.FindElement(By.XPath(".."))).Select(f => f.Text).ToArray(); vehicleGroupList.Items.AddRange(vehicleGroupNames); – Sam Basso Oct 25 '17 at 17:27