简体   繁体   中英

Populating a CheckedListBox with extracted labels from a CheckBoxList in Selenium C#

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.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM