如何在 Selenium 中從靜態下拉列表中選擇一個值?
Selenium 中 Select 類下可用於從靜態下拉列表中選擇值的各種方法。
它們列示如下:
selectByVisibleText(String args)
此方法在下拉列表中最常用。使用此方法在下拉列表和多選框中選擇選項非常簡單。它以字串作為引數,不返回值。
語法:
Select s = new Select(driver.findElement(By.id("<< id exp>>"))); s.selectByVisibleText("Selenium");selectByIndex(String args)
此方法獲取要在下拉列表中選擇的選項的索引。它以 int 作為引數,不返回值。
語法:
Select s = new Select(driver.findElement(By.id("<< id exp>>"))); s.selectByIndex(1);selectByValue(String args)
此方法獲取要在下拉列表中選擇的選項的值。它以字串作為引數,不返回值。
語法:
Select s = new Select(driver.findElement(By.id("<< id exp>>"))); s.selectByValue(“Testing”);
示例
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 SelectOptions{
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);
Select s = new Select(driver.findElement(By.xpath("//select[@name=’selType’]")));
// select an option by value method
s.selectByValue("name");
Thread.sleep(1000);
// select an option by index method
s.selectByIndex(0);
Thread.sleep(1000);
// select an option by visible text method
s.selectByVisibleText("By Subject");
Thread.sleep(1000);
driver.quit();
}
}
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP