如何从下拉列表中选择值 Selenium

如何选择下拉菜单 Selenium

以下是如何从下拉列表中选择值的分步过程 Selenium:

在处理下拉菜单之前 Selenium 并控制下拉框,我们必须做以下两件事:

  1. 导入包 org.openqa.selenium.support.ui.Select
  2. 将下拉框实例化为对象,选择 Selenium 网络驱动程序

例如,转到 Mercury 旅游注册页面 (https://demo.guru99.com/test/newtours/register.php),并注意那里的“国家”下拉框。

选择下拉菜单 Selenium

步骤1)导入“选择”包。

import org.openqa.selenium.support.ui.Select;

步骤2)将下拉元素声明为 Select 类的实例.

在下面的示例中,我们将此实例命名为“drpCountry”。

Select drpCountry = new Select(driver.findElement(By.name("country")));

步骤3)开始控制它。

我们现在可以使用任何可用的 Select 方法来选择下拉列表来开始控制“drpCountry” Selenium。下面的示例代码将选择选项“ANTARCTICA”。

drpCountry.selectByVisibleText("ANTARCTICA");

选择班级 Selenium

- 选择班级 Selenium 是用于实现 HTML SELECT 标记的方法。html select 标记提供了辅助方法来选择和取消选择元素。Select 类是一个普通类,因此使用 New 关键字来创建其对象并指定 Web 元素位置。

选择方法 Selenium

以下是最常用的方法 Selenium 下拉列表。

#1)selectByVisibleText()和deselectByVisibleText()

  • 选择/取消选择显示与参数匹配的文本的选项。
  • 参数: 特定选项的准确显示文本

示例:

drpCountry.selectByVisibleText("ANTARCTICA");

#2)selectByValue()和deselectByValue()

  • 选择/取消选择“value”属性与指定参数匹配的选项。
  • 请记住,并非所有下拉选项都具有相同的文本和“值”,如下例所示。
  • 参数: “value” 属性的值

示例:

SelectByValue 和 deselectbyvalue

drpCountry.selectByValue("234");

#3)selectByIndex()和deselectByIndex()

  • 选择/取消选择给定索引处的选项。
  • 参数: 要选择的选项的索引。

示例:

drpCountry.selectByIndex(0);

#4)isMultiple()

  • 如果下拉元素允许一次选择多个,则返回 TRUE;否则,返回 FALSE。
  • 参数: 不需要

例如:

if (drpCountry.isMultiple())
{
//do something here
}

#5)取消全部选择()

  • 清除所有选定的条目。仅当下拉元素支持多项选择时才有效。
  • 参数: 不需要

示例:

drpCountry.deselectAll();

选择方法的完整代码 Selenium

package newpackage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.By;

public class accessDropDown {
 public static void main(String[] args) { 
		System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
	    String baseURL = "https://demo.guru99.com/test/newtours/register.php";
	    WebDriver driver = new FirefoxDriver();
		driver.get(baseURL);

		Select drpCountry = new Select(driver.findElement(By.name("country")));
		drpCountry.selectByVisibleText("ANTARCTICA");

		//Selecting Items in a Multiple SELECT elements
		driver.get("http://jsbin.com/osebed/2");
		Select fruits = new Select(driver.findElement(By.id("fruits")));
		fruits.selectByVisibleText("Banana");
		fruits.selectByIndex(1);
 }
}

在多个 SELECT 元素中选择项目

我们也可以使用 选择可见文本() 方法在多 SELECT 元素中选择多个选项。作为示例,我们将 https://jsbin.com/osebed/2 作为基本 URL。它包含一个下拉框,允许一次选择多个。

在多个选择元素中选择项目

下面的代码将使用 selectByVisibleText() 方法选择前两个选项。

在多个选择元素中选择项目

总结

命令 描述
selectByVisibleText()/

取消选择可见文本()

根据显示的文本选择/取消选择一个选项
selectByValue()/

取消选择ByValue()

根据“value”属性的值选择/取消选择一个选项
selectByIndex()/

取消选择ByIndex()

根据索引选择/取消选择一个选项
是多个() 如果下拉元素允许一次选择多个,则返回 TRUE;否则,返回 FALSE
取消全部选择() 取消选择所有先前选择的选项

要控制下拉框,您必须首先导入 org.openqa.selenium.support.ui.Select 包,然后创建一个 Select 实例。

了解更多 readmore