WEB自动化(JAVA版)——特殊元素定位与操作-select下拉框

特殊元素定位与操作-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();
	}
}
发布了73 篇原创文章 · 获赞 2 · 访问量 3154

猜你喜欢

转载自blog.csdn.net/anniewhite/article/details/105344842