ディレクトリ
特別な要素の配置と操作選択ドロップダウンボックス
ページ要素がドロップダウンボックスの場合、このWeb要素をSelectオブジェクトとしてカプセル化できます。
- select = new Select(WebElement element);を選択します。
一般的に使用されるAPIを選択
- select.getOptions(); //すべてのオプションを取得
- select.selectByIndex(index); //インデックスに従って対応する要素を選択します
- select.selectByValue(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();
}
}