對於一般元素的操作,我們只要掌握本系列的第二,三章即可大致足夠。對於下拉菜單(Select)的操作,Selenium有專門的類Select進行處理。文檔地址為:http://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/Select.html
該類只有一個構造函數,Select(WebElement element),如果我們定位的元素並非Select,則會引發異常:UnexpectedTagNameException
- when element is not a SELECT
要懂得Select類的方法的使用,首先要先知道Html中,Select標簽的用法。在此不啰嗦,簡單提一下就是,Select有兩種模式,單選和多選,單選模式就是我們經常見到的下拉框,多選模式,在Select標簽中增加 multiple,例如<select name="phones" multiple>,顯示的樣式如下圖,多選的時候,需要按住ctrl+左鍵點擊
下面說說Select類的常用方法。
方法 | 說明 |
void deselectAll() | 取消所有選擇項,僅對下拉框的多選模式有效,若下拉不支持多選模式,則會拋出異常 UnsupportedOperationException(不支持的操作) |
void deselectByIndex(int index) | 取消指定index的選擇,index從零開始,僅對多選模式有效,否則拋出異常 UnsupportedOperationException(不支持的操作) |
void deselectByValue(String value) | 取消Select標簽中,value為指定值的選擇,僅對多選模式有效,否則拋出異常 UnsupportedOperationException(不支持的操作) |
void deselectByVisibleText(String Text) | 取消項的文字為指定值的項,例如指定值為Bar,項的html為 <option value="foo">Bar</option>,僅對多選模式有效,單選模式無效,但不會拋出異常 |
List<WebElement>getAllSelectedOptions() |
獲得所有選中項,單選多選模式均有效,但沒有一個被選中時,返回空列表,不會拋出異常 |
WebElement getFirstSelectedOption() |
獲得第一個被選中的項,單選多選模式均有效,當多選模式下,沒有一個被選中時,會拋出NoSuchElementException異常 |
List<WebElement>getOptions() |
獲得下拉框的所有項,單選多選模式均有效,當下拉框沒有任何項時,返回空列表,不會拋出異常 |
boolean isMultiple() |
判斷下拉框是否多選模式 |
void selectByIndex(int index) | 選中指定index的項,單選多選均有效,當index超出范圍時,拋出NoSuchElementException異常 |
void selectByValue(String value) | 選中所有Select標簽中,value為指定值的所有項,單選多選均有效,當沒有適合的項時,拋出NoSuchElementException異常 |
void selectByVisibleText(String text) | 選中所有項的文字為指定值的項,與deselectByValue相反,但單選多選模式均有效,當沒有適合的項時,拋出NoSuchElementException異常 |
看起來似乎很難記,實際很容易,select開頭的,單選多選均有效;deselect開頭的,僅對多選模式有效;返回選中項的,單選多選均有效,返回List的不會拋出異常。
下面用簡單例子,展示如何操作下拉菜單。我們在項目文件夾下,添加html文件夾,並增加一個dropdown.html,文件結構如下
dropdown.html的html代碼為
<!DOCTYPE html> <html> <head> <meta> <title>下拉列表</title> </head> <body> <form action=""> <select name="phones" multiple> <option value="華為">華為</option> <option value="三星">三星</option> <option value="中興">中興</option> <option value="小米">小米</option> </select> </form> </body> </html>
我們的目標是選中“中興”,代碼為
//得到WebDriver WebDriver driver=DriverHelper.CreateChromeDriver(); //轉到我們剛才編寫的html driver.get("D:/WorkSpace/SeleniumTest/html/dropdown.html"); //找到下拉框元素 WebElement element=driver.findElement(By.name("phones")); //轉化為Select Select select=new Select(element); //使用value也可以 select.selectByValue("中興"); //使用可見文字也可以 //select.selectByVisibleText("中興"); //使用index也可以 //select.selectByIndex(2);
最終執行的效果如下: