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