如何使用Selenium WebDriver和Java从下拉列表中选择一个项目?
我们可以使用 Selenium webdriver 从下拉列表中选择一个项目。Selenium 中的 Select 类用于处理下拉列表。在 html 文档中,下拉列表用 <select> 标签描述。
让我们考虑一下下面 <select> 标签的 html 代码。

为了利用 Select 类的各种方法,我们必须在代码中 **导入 org.openqa.selenium.support.ui.Select**。让我们看看如何使用 Select 方法选择一个项目 -
selectByVisibleText(arg) – 根据下拉列表中可见的文本选择一个项目,该文本与作为参数传递给方法的参数 arg 匹配。
语法 -
select = Select (driver.findElement(By.id ("txt")));
select.selectByVisibleText ('Text');
selectByValue(arg) – 根据下拉列表中选项的值选择一个项目,该值与作为参数传递给方法的参数 arg 匹配。
语法 -
select = Select (driver.findElement(By.id ("txt")));
select.selectByValue ('Val');
selectByIndex(arg) – 根据下拉列表中选项的索引选择一个项目,该索引与作为参数传递给方法的参数 arg 匹配。索引从 0 开始。
语法 -
select = Select (driver.findElement(By.id ("txt")));
select.selectByIndex (1);
示例
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 SelectDropDownItem{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String u ="https://tutorialspoint.com/selenium/selenium_automation_practice.htm"
driver.get(u);
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
// identify element
WebElement t=driver.findElement(By.xpath("//*[@name='continents']"));
//Select class for dropdown
Select select = new Select(t);
// select an item with text visible
select.selectByVisibleText("Australia");
// select an item with item index
select.selectByIndex(1);
driver.close();
}
}
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP