如何使用Selenium WebDriver和Java從下拉列表中選擇一個專案?


我們可以使用 Selenium webdriver 從下拉列表中選擇一個專案。Selenium 中的 Select 類用於處理下拉列表。在 html 文件中,下拉列表用 <select> 標籤描述。

讓我們考慮一下下面 <select> 標籤的 html 程式碼。

為了利用 Select 類的各種方法,我們必須在程式碼中 **匯入 org.openqa.selenium.support.ui.Select**。讓我們看看如何使用 Select 方法選擇一個專案 -

  • selectByVisibleText(arg) – 根據下拉列表中可見的文字選擇一個專案,該文字與作為引數傳遞給方法的引數 arg 匹配。

    語法 -

    select = Select (driver.findElement(By.id ("txt")));

    select.selectByVisibleText ('Text');

  • selectByValue(arg) – 根據下拉列表中選項的值選擇一個專案,該值與作為引數傳遞給方法的引數 arg 匹配。

    語法 -

    select = Select (driver.findElement(By.id ("txt")));

    select.selectByValue ('Val');

  • selectByIndex(arg) – 根據下拉列表中選項的索引選擇一個專案,該索引與作為引數傳遞給方法的引數 arg 匹配。索引從 0 開始。

    語法 -

    select = Select (driver.findElement(By.id ("txt")));

    select.selectByIndex (1);

示例

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 SelectDropDownItem{
   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://tutorialspoint.tw/selenium/selenium_automation_practice.htm"
      driver.get(u);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement t=driver.findElement(By.xpath("//*[@name='continents']"));
      //Select class for dropdown
      Select select = new Select(t);
      // select an item with text visible
      select.selectByVisibleText("Australia");
      // select an item with item index
      select.selectByIndex(1);
      driver.close();
   }
}

更新於: 2020-09-18

2K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告