gpt4 book ai didi

java - 我如何从下拉菜单中选择元素

转载 作者:行者123 更新时间:2023-11-30 06:05:23 28 4
gpt4 key购买 nike

在这里,我在 Common.java 类中创建一个通用方法,用于根据 visibleText 选择元素。在另一个类(NewTest.java)中,我调用该值selectByVisibleText。但是当我调试这个程序时它显示 发现错误:

org.openqa.selenium.support.ui.UnexpectedTagNameException:

元素应该是“select”,但却是“input”。那么我如何从下拉列表中选择员工?

1) Common.java

    public static String selectByVisibletext(String xPath,String inputData, WebDriver driver) {
WebElement webElement = driver.findElement(By.xpath(xPath));
try {
System.out.println(inputData);
System.out.println(xPath);
System.out.println(driver);
Select selectBox = new Select(webElement);
selectBox.selectByVisibleText(inputData);
}
catch (Exception e) {
System.out.println("error found : "+e);
}
return inputData;
}

1) NewTest.java

    String search = "//input[@class='select2-search__field']";

public void employee() {
Common.selectByVisibletext(search,"Employee", driver);
}

最佳答案

如果标签不是“选择”标签,您可以使用类似的东西:

public static String selectByVisibletext(String xPath,String inputData, WebDriver driver) {
WebElement webElement = driver.findElement(By.xpath(xPath));
try {
System.out.println(inputData);
System.out.println(xPath);
System.out.println(driver);
Select selectBox = new Select(webElement);
selectBox.selectByVisibleText(inputData);
}
catch (Exception e) {
if (e.getMessage().contains("UnexpectedTagNameException")) {
List<WebElement> dropDown = driver.findElements(By.xpath(xPath));
dropDown.forEach(dropElement -> {
if (dropElement.getAttribute("innerText").equals(inputData)) {
dropElement.click();
}
});
}
}
return inputData;
}

这个概念是使用列表中的选择器收集元素,然后找到与所需的可选元素匹配的元素,然后单击它。

首先单击“//input[@class='select2-search__field']”,然后找到所有下拉元素的选择器,然后将它们作为 WebElements 列表获取,并通过匹配您的文本进行选择。

关于java - 我如何从下拉菜单中选择元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51440891/

28 4 0