如何在不使用 Selenium 中的 Select 類方法的情況下在下拉列表中選擇特定值?


我們可以使用 findElements() 方法透過 Select 類的 findElements() 方法選擇下拉列表中的特定值。

示例

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 OptionsClick{
   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://tutorialspoint.tw/tutor_connect/index.php";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);
      // getting the list of elements with the xpath
      List<WebElement> opt = driver.findElements(By.xpath("//select[@name=’selType’]//option"));
      int s = opt.size();
      // Iterating through the list selecting the desired option
      for( int j = 0; j< opt.size();j++){
         // if the option is By Subject click that option
         if( opt.get(j).getText().equals("By Subject")){
            opt.get(j).click();
            break;
         }
      }
      driver.quit();
   }
}

更新於: 11 年 6 月 2020 日

5,000 多次瀏覽

啟動你的事業

完成課程並獲得認證

開始學習
廣告