如何在 selenium 中使用下拉列表?
我們可以使用 Selenium webdriver 從下拉列表中選擇一個選項。Select 類用於處理靜態下拉列表。透過 html 程式碼中的 <select> 標記識別下拉列表。
讓我們考慮用於 <select> 標記的以下 HTML 程式碼。

我們必須 匯入 org.openqa.selenium.support.ui.Select 以在我們的程式碼中使用 Select 類下的方法。讓我們看看一些 Select 方法−
selectByVisibleText(arg) - 如果下拉列表上顯示的文字與作為方法引數傳遞的引數 arg 相同時,選擇一個選項。
語法
sel = Select (driver.findElement(By.id ("option")));
sel.selectByVisibleText ("Selenium");
selectByValue(arg) - 如果下拉列表上的值與作為方法引數傳遞的引數 arg 相同時,選擇一個選項。
語法
sel = Select (driver.findElement(By.id("option")));
sel.selectByValue ("val");
selectByIndex(arg) - 如果下拉列表上的索引與作為方法引數傳遞的引數 arg 相同時,選擇一個選項。索引從 0 開始。
語法
sel = Select (driver.findElement(By.id("option")));
sel.selectByIndex(3);
示例
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 SelectItem{
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/selenium/selenium_automation_practice.htm"
driver.get(url);
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
// identify element
WebElement p=driver.findElement(By.xpath("//[@name='continents']"));
//Select class
Select sel= new Select(p);
// select with text visible
sel.selectByVisibleText("Africa");
// select with index
sel.selectByIndex(5);
driver.quit();
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP