将当前选择的选项作为文本/字符串用于 Selenium + Java 中的下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14936825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the currently selected option as text/string for a drop down in Selenium + Java
提问by Srivastava
I have a situation where I need to get the current selection from the drop down as a text or String and compare it for further assertion. But when I try the getText(), I get the complete list of items in the drop down. How can I get the currently selected item from drop down?
我有一种情况,我需要从下拉列表中将当前选择作为文本或字符串获取并进行比较以进行进一步的断言。但是当我尝试 getText() 时,我会在下拉列表中获得完整的项目列表。如何从下拉列表中获取当前选定的项目?
Hope my question makes sense, please let me know if anybody has done it before.
希望我的问题是有道理的,如果有人以前做过,请告诉我。
Thanks in Advance
提前致谢
回答by Srivastava
This is the code which worked for me
这是对我有用的代码
Select comboBox = new Select(driver.findElement(locator);
String selectedComboValue = comboBox.getFirstSelectedOption().getText();
Hope it help others too!!
希望它也能帮助其他人!!
回答by Manigandan
Try this code:
试试这个代码:
//Assume driver initialized properly some where else
Select sel = new Select(driver.findElement(By.xpath(Dropdown locator Id)));
String strCurrentValue = sel.getFirstSelectedOption();
//Print the Currently selected value
System.out.println(strCurrentValue);
Use the above value for assertion purpose.
将上述值用于断言目的。
回答by Will
Provided you know which text you're looking for.... This works for me
如果您知道要查找的文本.... 这对我有用
public String getValueFromDropDown(WebElement element, String compareText) {
List<WebElement> options = new Select(element).getAllSelectedOptions();
for (WebElement option : options){
if (option.getText().equals(compareText)){
return option.getText();
}
}
return null;
}
Note: The other answers grab the first selected item. This checks all available options.
注意:其他答案会抓住第一个选定的项目。这将检查所有可用选项。
回答by Neal
You can use the below option in selenium to get the text value :
您可以在 selenium 中使用以下选项来获取文本值:
Driver.findElement(By.id("id value")).getVisibleText("enter value name");