Reputation: 6470
I need to click on specified li
element using dropdown list: All subject areas
on website. The problem is: cannot click on specified li
element using Selenium.
For example, if I'm writting like:
String textInput = "Agricultural and Biological Sciences";
//...
// open the dropdown so the options are visible
driver.findElement(By.className("dropdown"));
// Get all of the options of dropdown list
WebElement ulElement = driver.findElement(By.cssSelector("ul.dropdown-options.dropdown-element"));
List<WebElement> opts = ulElement.findElements(By.xpath(".//li/a"));
And trying to choose specified li
element:
// Loop through the options and select the one that matches
for (WebElement opt : opts) {
if(opt.getText().equals(textInput)){
opt.click();
//...
}
}
The condition is simply skipped by the program.
If I changed to variant like:
// Loop through the options and select the one that matches
for (WebElement opt : opts) {
if(!opt.findElements(By.xpath("//*[contains(text(), '" + textInput + "')]")).isEmpty()) {
opt.click();
//...
}
}
The condition isn't ignored and successfully passes, but then the program doesn't click on the button, and the list is closed.
Can someone suggest me how to solve the problem here?
Upvotes: 1
Views: 884
Reputation: 7563
First, to appear the li
you need click this element:
driver.findElement(By.className("dropdown")).click();
Second, you need add wait
after click and add break
statement in the loop:
String textInput = "Agricultural and Biological Sciences";
WebElement ulElement = driver.findElement(By.cssSelector("ul.dropdown-options.dropdown-element"));
List<WebElement> opts = new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfNestedElementsLocatedBy(ulElement, By.xpath(".//li/a")));
//here, before click, just make sure your `li` printed all the text
for(WebElement opt :opts) {
System.out.println("get text : " +opt.getText());
}
for (WebElement opt : opts) {
if(opt.getText().equals(textInput)){
opt.click();
//here
break;
}
}
After you have successfully clicked the one you want, you have switched to another page, so the li
element after that no longer exists. So you need a break
statement.
Upvotes: 1
Reputation: 193248
To click()
on the element with text as Agricultural and Biological Sciences (miscellaneous) from the dropdown you need to induce WebDriverWait for the elementToBeClickable()
and you can use the following Locator Strategies:
xpath:
driver.navigate().to("https://www.scimagojr.com/journalrank.php?country=UA&page=1");
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[normalize-space()='All subject areas']"))).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[normalize-space()='All subject areas']//following-sibling::ul[1]//li/a[normalize-space()='Agricultural and Biological Sciences']"))).click();
Browser Snapshot:
Upvotes: 1