Selenium常用API的使用java语言之16-下拉框选择

有时我们会碰到下拉框,WebDriver提供了Select类来处理下接框。
如百度搜索设置的下拉框,如下图:

搜索下拉框实现代码如下:

<select id="nr" name="NR">
  <option value="10" selected>每页显示 10 条</option>
  <option value="20">每页显示 20 条</option>
  <option value="50">每页显示 50 条</option>
<select>

操作下接框代码如下:

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;
 
 
public class SelectDemo {
 
  public static void main(String[] args) throws InterruptedException {
 
    WebDriver driver = new ChromeDriver();
    driver.get("https://www.baidu.com");
 
    driver.findElement(By.linkText("设置")).click();
    driver.findElement(By.linkText("搜索设置")).click();
    Thread.sleep(2000);
 
    //<select>标签的下拉框选择
    WebElement el = driver.findElement(By.xpath("//select"));
    Select sel = new Select(el);
    sel.selectByValue("20");
    Thread.sleep(2000);
 
    driver.quit();
  }
}

Select类用于定位select标签。 selectByValue()方法符用于选取标签的value值。

猜你喜欢

转载自www.cnblogs.com/zhizhao/p/11303335.html