How to use select list in selenium?

前端 未结 4 1970
说谎
说谎 2020-12-20 12:58

I\'m trying to select an element from a select list in selenium using java with WebDriver - based syntax.

I\'ve got the select list by

    elements =         


        
相关标签:
4条回答
  • 2020-12-20 13:48
    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<WebElement> Options = dropDown.getOptions();
    for(WebElement option:Options){
        if(option.getText().equals(valueToSelect)) {
          option.click(); //select option here;       
        }               
    }
    

    If this is slower, then consider something like

    dropDown.selectByValue(value);
    or
    
    dropDown.selectByVisibleText(text);
    
    0 讨论(0)
  • 2020-12-20 13:49

    Try to do it like this :

    //method to select an element from the dropdown

    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);
    }
    

    //method to highlight the element

    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, "");
    
        }
    
    }
    
    0 讨论(0)
  • 2020-12-20 13:53

    A little side note which applies to Java:

    In my case, when I was writing the test according the example of @nilesh, I got a strange error, that the constructor is invalid. My import was:

    import org.openqa.jetty.html.Select;
    

    If you happen to have similar errors, you have to correct that import to this:

    import org.openqa.selenium.support.ui.Select;
    

    If you use this second import, everything will work.

    0 讨论(0)
  • 2020-12-20 13:56
    element = driver.findElements(By.xpath("//form[@action='inquiry/']/p/select[@name='myselect']/option[*** your criteria ***]"));
    if (element != null) {
        element.click();
    }
    

    find the option, and then click it

    0 讨论(0)
提交回复
热议问题