特殊元素定位與操作-select下拉框
如果頁面元素是一個下拉框,我們可以將此web元素封裝爲Select對象。
- Select select = new Select(WebElement element);
Select對象常用api
- select.getOptions(); //獲取所有選項
- select.selectByIndex(index); //根據索引選中對應的元素
- select.selectByValue(value); //選擇指定value值對應的選項
- select.selectByVisibleText(text); //選中文本值對應的選項
代碼示例
package com.test;
import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class SpecialElementLocate {
private static ChromeDriver chromeDriver;
public static void main(String[] args) throws InterruptedException {
//select下拉框處理
openChrome();
chromeDriver.get("http://www.baidu.com");
chromeDriver.manage().window().maximize();
chromeDriver.findElement(By.xpath("//div[@id='u1']/a[text()='設置']")).click();
chromeDriver.findElement(By.xpath("//a[text()='高級搜索']")).click();
Thread.sleep(2000);
//定位時間下拉框
WebElement webElement = chromeDriver.findElement(By.name("gpc"));
//把WebElement封裝成Select對象
Select select = new Select(webElement);
//select下拉框,索引值從0開始
select.selectByIndex(1);
Thread.sleep(2000);
select.selectByVisibleText("最近一月");
}
public static void openChrome() {
System.setProperty("webdriver.chrome.driver", "src/test/resources/chromedriver.exe");
//1.打開Chrome瀏覽器
chromeDriver = new ChromeDriver();
}
}