Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

Selenium Java : Dropdown items are updated dynamically

Any inputs will be appreciated: The web application I am working on does not have the "select" tag, and the items in the drop-down get updated dynamically. Meaning when I click on the down arrow of the dropdown menu, it would show about 10 items and when I scroll down the "scrollbar of the dropdown" more items are populated. While I can select an item by typing in the value in the "field" of the dropdown box and by then clicking on the "runtime" created xpath Eg. driver.findElement(By.xpath("//li[@text()='USA']).click which works fine for selecting any item, I would need to get all the items in that dropdown. Is there a way this can be achieved?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

driver.findElement(By by) and driver.findElements(By by) scopes the while DOM.

you can target a small area of the DOM with: element.findElement(By by) and element.findElements(By by)

Using this:

WebElement dropdown = driver.findElement(By.DROPDOWN LOCATOR);
List<WebElement> options = dropdown.findElements(By.OPTION LOCATOR);

You still need the OPTION LOCATOR. But it is easier to achieve, it will collect child elements from the parrent element only.

Select methods would look like this:

public void selectByText(List<EebElement> options, String text) {
    for (WebElement element: options) {
        if (element.getText().equals(text)) {
            element.click();
            break;
        }
    }
}

public void selectByValue(List<EebElement> options, String value) {
    for (WebElement element: options) {
        if (element.getAttribute("value").equals(value)) {
            element.click();
            break;
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...