Selenium Java:下拉项动态更新动态、Selenium、Java

2023-09-08 00:11:57 作者:抽烟因为烟不乖i

我正在开发的 Web 应用程序没有选择"选项.标签,并且下拉列表中的项目会动态更新.这意味着当我单击下拉菜单的向下箭头时,它将显示大约 10 个项目,当我向下滚动下拉菜单的滚动条"时填充了更多项目.虽然我可以通过在字段"中输入值来选择项目的下拉框,然后单击运行时";创建 xpath 例如.driver.findElement(By.xpath("//li[@text()='USA']).click 可以很好地选择任何项目,我需要获取所有项目那个下拉菜单.有什么方法可以实现吗?

The web application I am working on does not have the "select" tag, and the items in the dropdown 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 then by 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?

推荐答案

driver.findElement(By by)driver.findElements(By by) 作用域是 while DOM.

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

您可以通过以下方式定位 DOM 的一小部分区域:element.findElement(By by)element.findElements(By by)

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

使用这个:

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

您仍然需要 OPTION LOCATOR.但是比较容易实现,只会从父元素中收集子元素.

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

选择方法如下所示:

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;
        }
    }
}
 
精彩推荐