Selenium WebDriver 和下拉框。
我们可以使用 Selenium webdriver 处理下拉菜单。Selenium 中的静态下拉菜单通过 **Select** 类处理,并且下拉菜单应在 html 代码中使用 **<select>** 标签识别。
让我们看看静态下拉菜单的 html 代码。
我们必须在代码中添加 **import org.openqa.selenium.support.ui.Select** 语句才能使用 Select 类中可用的方法。从下拉菜单中选择选项的方法如下所示:
selectByValue(val) – 选择其 value 属性与传递给方法的参数匹配的选项。仅当下拉选项的 html 代码中包含 value 属性时,才能使用此方法。
语法:Select sl = new Select (driver.findElement(By.name("name"))); sl.selectByValue ('value');
selectByVisibleText(txt) – 选择其可见文本与传递给方法的参数匹配的选项。
语法:Select sl = new Select (driver.findElement(By.name("name"))); sl.selectByVisibleText ('Selenium');
selectByIndex(n) – 选择其索引与传递给方法的参数匹配的选项。索引从零开始。
语法:Select sl = new Select (driver.findElement(By.name("name"))); sl.selectByIndex(3);
示例
代码实现。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.support.ui.Select public class SelectDropDown{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String u = "https://tutorialspoint.com/selenium/selenium_automation_practice.htm" driver.get(u); driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); // identify dropdown WebElement d=driver.findElement(By.xpath("//*[@name='continents']")); //dropdown handle with Select class Select sl = new Select(d); // select option with text visible sl.selectByVisibleText("Africa"); // select option with index sl.selectByIndex(4); driver.quit(); } }
广告