简体   繁体   English

使用带有Java的Selenium WebDriver获取选择的选项

[英]Get selected option using Selenium WebDriver with Java

I'm new to Selenium WebDriver. 我是Selenium WebDriver的新手。 I'm testing a drop down list. 我正在测试一个下拉列表。 Here is the code I used to select an item from the drop down. 这是我用来从下拉菜单中选择项目的代码。

Select dropdown = new Select(driver.findElement(By.xpath("//select")));
dropdown.selectByValue("FEM");

This is working fine, but what I need is to get selected item as a text. 这工作正常,但是我需要的是将所选项目作为文本。 For an example, under the value = FEM , the text displays is female. 例如,在value = FEM ,文本显示为女性。 I need to get the text as Selected value is female. 我需要获取文本,因为“选定值”是女性。

I've searched some articles and none of this worked. 我搜索了一些文章,但这些都没有。 Please help. 请帮忙。 :) :)

Select has getFirstSelectedOption() method. Select具有getFirstSelectedOption()方法。 From there you can use getText() 从那里可以使用getText()

Select dropdown = new Select(driver.findElement(By.xpath("//select")));
dropdown.selectByValue("FEM");

WebElement option = dropdown.getFirstSelectedOption();
String text = option.getText();

You can use element1.selectByVisibleText(value); 您可以使用element1.selectByVisibleText(value); if you want to set the option using text instead of value 如果要使用文本而不是值来设置选项

If you want to get the value use element1.getAllSelectedOptions().get(0).getText() 如果要获取值,请使用element1.getAllSelectedOptions().get(0).getText()

or element1.getFirstSelectedOption() element1.getFirstSelectedOption()

而不是使用dropdown.selectByvalue("FEM")使用dropdown.selectByVisibleText("FEM")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Selenium WebDriver 和 Java 获取选定的选项 - How to get selected option using Selenium WebDriver with Java 当元素不是选择类型输入时,如何使用Selenium Webdriver Java从下拉列表中获取所有选项值? - how to get all option values from dropdown using selenium webdriver java when the element is not a select type input? 得到<p>使用 Selenium webdriver 的内容 - Java - Get <p> content using Selenium webdriver - Java 使用Java获取Selenium WebDriver的页面标题 - Get page title with Selenium WebDriver using Java 通过 Java 使用 Selenium webdriver 缺少 size() 选项 - size() option is missing using Selenium webdriver through Java 如何使用 selenium webdriver 和 Java 从剑道下拉菜单中选择一个选项 - How to select an option from the kendo dropdown using selenium webdriver and Java 在 Java 中使用 Selenium WebDriver - Using Selenium WebDriver with Java 使用Java的Selenium Webdriver - Selenium Webdriver using java 如何使用Selenium WebDriver(2)从dojo组合框中获取选定的值 - How to get the selected value from a dojo combobox using Selenium WebDriver(2) Selenium/Java:在下拉菜单中获取当前选定选项的索引/位置 - Selenium/Java: get index/position of currently selected option in a dropdown menu
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM