如何在 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.com/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