如何使用 Java 中的 Selenium WebDriver 获取选中的选项?
seleniumautomation testingtesting tools更新于 2026/2/11 12:37:17
我们可以在 Selenium WebDriver 的下拉菜单中获取选中的选项。getFirstSelectedOption() 方法返回下拉菜单中选中的选项。获取选项后,我们可以应用 getText() 方法获取文本。
我们来考虑下面的下拉菜单,Continents 获取其选中的项。 −

示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.Select
public class SelecedItem{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String u =" https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm"driver.get(u);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// 识别元素
WebElement t=driver.findElement(By.xpath("//*[@name='continents']"));
// 选择下拉菜单的类
Select select = new Select(t);
// 选择一个可见文本的项目
select.selectByVisibleText("Australia");
// 使用 getFirstSelectedOption() 获取选定选项及其文本
WebElement o = select.getFirstSelectedOption();
String selectedoption = o.getText();
System.out.println("Selected element: " + selectedoption);
driver.close();
}
}
输出


