Selenium Java : Dropdown items are updated dynamically

橙三吉。 提交于 2021-01-20 13:37:13

问题


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?


回答1:


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;
        }
    }
}


来源:https://stackoverflow.com/questions/65507887/selenium-java-dropdown-items-are-updated-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!