如何在 Selenium 中获取下拉菜单中的所有选项?

software testingautomation testingselenium web driver更新于 2026/2/10 14:07:17

我们可以借助 Select 类(该类包含 getOptions() 方法)提取 Selenium 下拉菜单中的所有选项。该方法将检索 Select 标签上的所有选项,并返回一个 Web 元素列表。此方法不接受任何参数。

示例

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 java.util.List;
import org.openqa.selenium.support.ui.Select;
public class DropdownOptions{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url = " https://www.tutorialspoint.com/tutor_connect/index.php";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      Select s = new Select(driver.findElement(By.xpath("//select[@name=’selType’]")));
      // 使用 getOptions() 获取下拉菜单中的选项列表
      List <WebElement> op = s.getOptions();
      int size = op.size();
      for(int i =0; i<size ; i++){
         String options = op.get(i).getText();
         System.out.println(options);
      }
      driver.quit()
   }
}

相关文章