Selenium+java - 下拉框處理

常見下拉框也分兩種:一種是標準控件和非標準控件(通常爲前端開發人員本身封裝的下拉框),本篇文章中將重點講解標準下拉框操做。html

一、Select提供了三種選擇某一項的方法

  • select.selectByIndex # 經過索引定位
  • selectByValue # 經過value值定位
  • selectByVisibleText # 經過可見文本值定位

使用說明:

  • index索引是從「0」開始;
  • value是option標籤中value屬性值定位;
  • VisibleText是在option是顯示在下拉框的文本;

二、Select提供了三種返回options信息的方法

  • getOptions() # 返回select元素全部的options
  • getAllSelectedOptions() # 返回select元素中全部已選中的選項
  • getFirstSelectedOption() # 返回select元素中選中的第一個選項

三、Select提供了四種取消選中項的方法

  • select.deselectAll() # 取消所有的已選擇項
  • deselectByIndex() # 取消已選中的索引項
  • deselectByValue() # 取消已選中的value值
  • deselectByVisibleText() # 取消已選中的文本值

四、被測頁面代碼

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Select控件練習案例</title>
</head>
<body>

<h4>請選擇你的英雄:</h4>
<select id="select">
    <option value="1">李白</option>
    <option selected="selected" value="2">韓信</option>
    <option value="3">典韋</option>
    <option value="4"></option>
</select>
</body>
</html>

具體示例代碼以下:前端

package com.brower.demo; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.Select; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.util.concurrent.TimeUnit; public class TestSelectDemo { WebDriver driver; @BeforeClass public void beforeClass() { System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe"); driver = new ChromeDriver(); } @Test public void testSelectDemo() { //打開測試頁面
        driver.get("file:///C:/Users/Administrator/Desktop/SelectDemo.html"); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS); //獲取select元素對象
        WebElement element = driver.findElement(By.id("select")); Select select = new Select(element); //根據索引選擇,選擇第1個英雄:李白
        select.selectByIndex(0); //根據value值選擇第4個英雄:凱
        select.selectByValue("4"); //根據文本值選擇第2個英雄:韓信
        select.selectByVisibleText("韓信"); //判斷是否支持多選
 System.out.println(select.isMultiple()); } @AfterClass public void afterClass() { driver.quit(); } }

以上即是關於select控件處理的演示案例,具體實踐還須要結合實際的工做須要來進行。java

原文出處:https://www.cnblogs.com/longronglang/p/11285956.htmlweb

相關文章
相關標籤/搜索