简体   繁体   中英

Selenium webdriver not working for multiple dynamic dropdowns using java

I have multiple dropddowns which are created dynamically on condition.

My Java code::

Initially ->

WebElement eleOpt = driver.findElement(By.xpath("//*[@id='id_0_" + value1+ "'" + "]/div/div"));
eleOpt.click();

Thread.sleep(200);

WebElement clickSelectedEle = driver.findElement(By.xpath("//custom-select[@id='id_0_" + value1+ "'" + "]/div/div[2]/ul/li[" + Integer.parseInt(value2) + "]"));
clickSelectedEle.click();

Note: value1 and value2 are dynamic values which will be passed in the method.

Automatically 2 dropdowns are getting clicked automatically but for third one its throwing below error:

Error -

org.openqa.selenium.NoSuchElementException: Unable to locate element: //custom-select[@id='id_0_2']/div/div[2]/ul/li[0]

HTML Code (Angular 2):

<caption class="blind">{{a11y}} {{name}}.</caption>

<div class="static" (click)="toggle()">
    <div class="selected">
        {{name}}
    </div>
</div>

<div class="open">
    <ul>
        <li id='{{option.code}}' (click)="changeval(option.code || option.id)" *ngFor="let option of options; let i = index" [ngClass]="{ 'active' : (selected && selected===i) }">
            <caption class="blind">option: {{option.name}}.</caption>
            <span>{{option.name}}</span>
        </li>
    </ul>
</div>

Please suggest what can be done.

One option is add a selenium wait.until condition

WebDriverWait wait = new WebDriverWait(getDriver(), 10);
wait.until(ExpectedConditions.presenceOfElementLocated(By.css("YourCssPath")));

You could use also any By.class, id,...option, I prefer to use By.class, or By.id in place to use css or regular expressions, first option are faster

200 ms is really less time. As @cralffaro has suggested use WebDriverWait or You should use FluentWait before performing action

Code of FluentWait

WebElement waitsss(WebDriver driver, By elementIdentifier){
     Wait<WebDriver> wait =
                new FluentWait<WebDriver>(driver).withTimeout(60, TimeUnit.SECONDS)
                                                 .pollingEvery(1, TimeUnit.SECONDS)
                                                 .ignoring(NoSuchElementException.class);

        return wait.until(new Function<WebDriver, WebElement>()
                {
                    public WebElement apply(WebDriver driver) {
                           return driver.findElement(elementIdentifier);
                    }
                });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM