如何使用 java & selenium 从下拉列表中按值 select 元素?
how to select element by value from dropdown with java & selenium?
我正在尝试从下拉列表中 select 国家代码,其中元素没有索引或 ID 我只能 select 按值,我尝试使用 SelectByValue 和 VisibleText 两者都没有工作也试图列出元素并在它们上循环但也没有用
更新:
它给我错误:org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been “select” but was “button”
我如何 select 从带有元素列表的按钮 ??
代码如下:
public void selectInDropDownMenuCountryCode(final WebDriver driver, final By selector, final String selection) {
_wait.until(ExpectedConditions.visibilityOfElementLocated(selector));
final Select select = new Select(driver.findElement(selector));
//select.selectByVisibleText(selection);
//select.selectByValue(selection);
String code;
List<WebElement> optionsD = select.getOptions();
for (WebElement option : optionsD) {
code = option.getAttribute("value");
if (code == selection) {
option.click();
break;
}
}
}
html的截图
如果您引用 HTML
,您会看到 Dropdown
不是使用 HTML Select
标记构建的。所以你不能使用下面的方法:-
- select按值
- select按索引
- select按可见文本
您必须使用常规方法来识别元素以处理下拉菜单。例如:尝试通过识别元素单击下拉列表,然后再次单击国家/地区名称以 select 值。
尝试使用简单的click()
方法来select所需的下拉选项:
_wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(text(), 'Egypt (+20)')]"))).click();
XPath
像 "//a[@country='Egypt']"
或 "//a[@value='EG']"
似乎也适用
请注意,在单击其选项之前,您应该先单击相应的元素以打开下拉菜单
我正在尝试从下拉列表中 select 国家代码,其中元素没有索引或 ID 我只能 select 按值,我尝试使用 SelectByValue 和 VisibleText 两者都没有工作也试图列出元素并在它们上循环但也没有用
更新:
它给我错误:org.openqa.selenium.support.ui.UnexpectedTagNameException: Element should have been “select” but was “button”
我如何 select 从带有元素列表的按钮 ??
代码如下:
public void selectInDropDownMenuCountryCode(final WebDriver driver, final By selector, final String selection) {
_wait.until(ExpectedConditions.visibilityOfElementLocated(selector));
final Select select = new Select(driver.findElement(selector));
//select.selectByVisibleText(selection);
//select.selectByValue(selection);
String code;
List<WebElement> optionsD = select.getOptions();
for (WebElement option : optionsD) {
code = option.getAttribute("value");
if (code == selection) {
option.click();
break;
}
}
}
html的截图
如果您引用 HTML
,您会看到 Dropdown
不是使用 HTML Select
标记构建的。所以你不能使用下面的方法:-
- select按值
- select按索引
- select按可见文本
您必须使用常规方法来识别元素以处理下拉菜单。例如:尝试通过识别元素单击下拉列表,然后再次单击国家/地区名称以 select 值。
尝试使用简单的click()
方法来select所需的下拉选项:
_wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[contains(text(), 'Egypt (+20)')]"))).click();
XPath
像 "//a[@country='Egypt']"
或 "//a[@value='EG']"
似乎也适用
请注意,在单击其选项之前,您应该先单击相应的元素以打开下拉菜单