如何在selenium中使用选择列表?
我正在尝试使用基于WebDriver语法的java从selenium中的选择列表中选择一个元素。
我有选择列表
elements = driver.findElements(By.xpath("//form[@action='inquiry/']/p/select[@name='myselect']")); if (elements.size() == 0) { return false; } if (guests != null) { //what do I do here? }
我怎么做?
WebElement select = driver.findElement(By.name("myselect")); Select dropDown = new Select(select); String selected = dropDown.getFirstSelectedOption().getText(); if(selected.equals(valueToSelect)){ //already selected; //do stuff } List Options = dropDown.getOptions(); for(WebElement option:Options){ if(option.getText().equals(valueToSelect)) { option.click(); //select option here; } }
如果这个比较慢,那就考虑一下
dropDown.selectByValue(value); or dropDown.selectByVisibleText(text);
适用于Java的一点注意事项:
在我的情况下,当我根据@nilesh的例子编写测试时,我得到一个奇怪的错误,构造函数是无效的。 我的导入是:
import org.openqa.jetty.html.Select;
如果您碰巧有类似的错误,则必须更正导入到此:
import org.openqa.selenium.support.ui.Select;
如果你使用第二次导入,一切都会工作。
element = driver.findElements(By.xpath("//form[@action='inquiry/']/p/select[@name='myselect']/option[*** your criteria ***]")); if (element != null) { element.click(); }
找到该选项,然后click
它
尝试这样做:
//从下拉列表中选择元素的方法
public void selectDropDown(String Value){
webElement findDropDown=driver.findElements(By.id="SelectDropDowm"); wait.until(ExpectedConditions.visibilityOf(findDropDown)); super.highlightElement(findDropDown); new Select(findDropDown).selectByVisibleText(Value); }
//突出显示元素的方法
public void highlightElement(WebElement element){
for (int i = 0; i < 2; i++) { JavascriptExecutor js = (JavascriptExecutor) this.getDriver(); js.executeScript( "arguments[0].setAttribute('style', arguments[1]);", element, "color: yellow; border: 3px solid yellow;"); js.executeScript( "arguments[0].setAttribute('style', arguments[1]);", element, ""); } }