­

使用SeleniumWebdriver操作下拉框菜單DropDown

  • 2019 年 10 月 5 日
  • 筆記
本文將介紹如何處理下拉框選項和多選操作

從下拉框中選擇–>選項

在控制下拉框之前,我們必須做以下兩件事:

  1. 導入包org.openqa.selenium.support.ui.Select
  2. 在WebDriver中將下拉框實例化為Select對象

例如,進入Mercury Tours的註冊頁面(http://demo.guru99.com/test/newtours/register.php), 看到這裡的Country下拉框。

在這裡插入圖片描述

在這裡插入圖片描述

第一步: 導入Select包;

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

第二步 將下拉元素聲明為Select類的實例。在下面的示例中,我們將這個實例命名為drpCountry;

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

第二步 現在,我們可以開始使用任何可用的選擇方法來控制drpCountry; 下面的示例程式碼將選擇「ANTARCTICA」選項:

drpCountry.selectByVisibleText("ANTARCTICA");  

選擇項中有多個元素

我們還可以使用selectByVisibleText()方法在一個多選擇元素中選擇多個選項。 例如我們將以http://jsbin.com/osebed/2作為測試的URL:它包含一個下拉框,允許一次選擇多個選項。

在這裡插入圖片描述

下面的程式碼將使用selectByVisibleText()方法選擇前兩個選項:

在這裡插入圖片描述

選擇的方法(5種)

下面是下拉列表中最常用的方法:

  • selectByVisibleText()和deselectByVisibleText()

1、通過選項的文本進行操作:選擇/取消選擇; 2、Parameter:指定選項對應的文本

  • selectByValue() 和deselectByValue()

1、通過選項的屬性值進行操作:選擇/取消選擇 2、Parameter:屬性的值; 3、注意:並非所有下拉選項都具有相同的文本和「value」,如下面的示例所示:

在這裡插入圖片描述

  • selectByIndex() 和 deselectByIndex()

1、通過選項的索引值(下標)進行操作:選擇/取消選擇 2、Parameter參數:選擇項對應的索引值(下標)

  • isMultiple()

1、如果下拉元素允許多選,則返回TRUE;否則返回FALSE。 2、參數:不需要參數

  • deselectAll()

1、取消所有選中選項;注意,只有當下拉元素支援多選時,這才有效。 2、參數:不需要參數

以下是上文中的完整程式碼:

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.firefox.marionette","C:\geckodriver.exe");          String baseURL = "http://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");            //在多個選項中選擇          driver.get("http://jsbin.com/osebed/2");          Select fruits = new Select(driver.findElement(By.id("fruits")));          fruits.selectByVisibleText("Banana");          fruits.selectByIndex(1);   }  }