问题
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