如何在 Selenium 2 中選擇/獲取下拉選項?


我們可以在 Selenium webdriver 中選擇下拉選項。可以使用 **Select** 類來操作下拉選單。在 HTML 中,**select** 標籤用於表示下拉選單,**option** 標籤用於表示下拉選單中的專案。

讓我們研究一下下拉選單的 HTML 結構。

我們需要新增語句 - **import org.openqa.selenium.support.ui.Select** 來使用 Select 類的 方法。Select 類的 方法如下所示:

  • selectByIndex(n) - 根據下拉選單中選項的索引選擇一個選項。索引 n 作為引數傳遞給方法。索引從 0 開始。

    語法:

    Select s = Select (driver.findElement(By.name("select-dropdown")));
    s.selectByIndex(0);
  • selectByValue(n) - 根據下拉選單中選項的值選擇一個選項。值 n 作為引數傳遞給方法。

    語法:

    Select s = Select (driver.findElement(By.name ("select-dropdown")));
    s.selectByValue("value");
  • selectByVisibleText(n) - 根據下拉選單中可見的文字選擇一個選項。可見文字 n 作為引數傳遞給方法。

    語法:

    Select s = Select (driver.findElement(By.name ("select-dropdown")));
    s.selectByValue("text");

示例

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 DropDownSelect{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",       "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      String url = "https://tutorialspoint.tw/selenium/selenium_automation_practice.htm";
      driver.get(url);
      // identify element
      WebElement m=driver
      .findElement(By.xpath("//*[@name='continents']"));
      //Select class for dropdown
      Select s = new Select(m);
      // select with text visible
      s.selectByVisibleText("Australia");
      // select with index
      s.selectByIndex(2);
      driver.close();
   }
}

輸出

更新時間: 2021年2月1日

828 次瀏覽

啟動你的 職業生涯

透過完成課程獲得認證

開始學習
廣告