Gecko 驅動程式,使用 Selenium 從下拉列表中選擇值
我們可以藉助 geckodriver.exe 可執行檔案在 Firefox(版本>47)中使用 Selenium webdriver 指令碼。首先,我們必須從以下連結下載此檔案:
https://github.com/mozilla/geckodriver/releases

導航到上述 URL 後,我們必須根據當前使用的作業系統(Windows、Linux 或 Mac)單擊一個連結。下載完成後,將建立一個 zip 檔案。我們必須解壓縮 zip 檔案並將 geckodriver.exe 檔案儲存在所需位置。
然後,我們必須使用 System.setProperty 方法配置 geckodriver.exe 檔案的路徑,並同時建立 FirefoxDriver 類的物件。
要從下拉列表中選擇一個值,我們必須使用 Select 類。html 程式碼中的下拉列表由
Select 類中有多種方法可用於從下拉列表中選擇選項:
selectByIndex – 將下拉列表要選擇的選項的索引作為引數傳遞給此方法。索引從 0 開始。
WebElement e = driver.findElement(By.id("slc"));
Select s = new Select(e);
s.selectByIndex(0);selectByValue – 將下拉列表要選擇的選項的 value 屬性作為引數傳遞給此方法。下拉列表中的選項應具有 value 屬性,以便可以使用此方法。
WebElement e = driver.findElement(By.id("slc"));
Select s = new Select(e);
s.selectByValue("option 1");selectByVisibleText – 將下拉列表要選擇的選項的可視文字作為引數傳遞給此方法。
WebElement e = driver.findElement(By.id("slc"));
Select s = new Select(e);
s.selectByVisibleText("Selenium");讓我們來看一個下拉列表及其 html 程式碼的示例:

示例
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.Select
public class DrpDwnValue{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("http://www.uitestpractice.com/Students/Select");
//identify dropdown
WebElement m = driver.findElement(By.id("countriesSingle"));
//select option by index
Select s = new Select(m);
s.selectByIndex(0);
//get option selected
String st = s.getFirstSelectedOption().getText();
System.out.println("Option selected by Index: " + st);
//select option by value
s.selectByValue("england");
//get option selected
String r = s.getFirstSelectedOption().getText();
System.out.println("Option selected by Value: " + r);
//select option by visible text
s.selectByVisibleText("United states of America");
//get option selected
String l = s.getFirstSelectedOption().getText();
System.out.println("Option selected by Visible Text: " + l);
driver.quit();
}
}輸出

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP