Selenium - How to check and increase the value of a dropdown if it is already present?

I am trying to automate an application using Selenium Webdriver (Java). My web application has an Add button. After clicking the Add button, the dropdown list will be enabled. If it is clicked again, a second dropdown menu will appear. Each subsequent ID of the dropdown will be displayed on page 1, page 2, page 3, etc.

What I want to do is when I open the page, I need to find out if any dropdown menu is present on the page, if yes, then select the next dropdown menu and then select a value from the dropdown.

This is my current code where I manually select each dropdown and select their respective values ​​.:

driver.findElement(By.id("addPage")).click();
new Select(driver.findElement(By.id("page0"))).selectByVisibleText("ABCD");
driver.findElement(By.id("addPage")).click();
Thread.sleep(1000);
new Select(driver.findElement(By.id("page1"))).selectByVisibleText("CDEF");
driver.findElement(By.id("addPage")).click();
Thread.sleep(1000);
new Select(driver.findElement(By.id("page2"))).selectByVisibleText("EFGH");
driver.findElement(By.id("addContact")).click();

      

+3


source to share


2 answers


I think you can find any select element from id

starting with page

, get the attribute value id

and click the dropdown from the next page. Implementation example:

WebElement existingPage = driver.findElement(By.cssSelector("select[id^=page]"));

String nextPageID = Integer.toString(Integer.parseInt(existingPage.getAttribute("id").replaceAll("\\D+", "")) + 1);
Select nextPage = new Select(driver.findElement(By.id("page" + nextPageID)));

      



And as @Iridann correctly pointed out, to check for existence, catch the exception NoSuchElementException

:

try {
    WebElement existingPage = driver.findElement(By.cssSelector("select[id^=page]"));
    // ...
} catch (NoSuchElementException e) {
    // no pages found
}

      

+2


source


I would try to do something along the lines of the next line, assuming that you won't have any other dropdowns present on this page (which I assume from your question is).

try {
driver.findElement(By.tagName("select"))
} catch (NoSuchElementException e) {
//create first dropdown
}

      



You can try and populate an array with the id of each select element on the page and find the presence of one that matches the pattern "page \ d" and navigate from there.

+2


source







All Articles