我需要使用下拉列表单击指定的li
元素:All subject areas
上的website。问题是:无法使用硒单击指定的li
元素。
例如,如果我要写:
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"));
并尝试选择指定的li
元素:
// Loop through the options and select the one that matches
for (WebElement opt : opts) {
if(opt.getText().equals(textInput)){
opt.click();
//...
}
}
条件只是被程序跳过。
如果我更改为类似的变体:
// 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();
//...
}
}
条件不会被忽略并成功通过,但是程序不会单击按钮,并且列表已关闭。
有人可以建议我在这里解决问题吗?
首先,要显示li
,请单击此元素:
driver.findElement(By.className("dropdown")).click();
第二,您需要在循环中添加break
语句:
for (WebElement opt : opts) {
if(opt.getText().equals(textInput)){
opt.click();
//here
break;
}
}
成功单击所需的页面后,您已切换到另一页,因此此后的li
元素不再存在。因此,您需要一个break
语句。
到文本为[[农业和生物科学(杂项)的元素上的 xpathclick()
,您需要为elementToBeClickable()
引入WebDriverWait,并且可以使用以下Locator Strategies:] >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 categories']"))).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//div[normalize-space()='All subject categories']//following-sibling::ul[1]//li/a[normalize-space()='Agricultural and Biological Sciences (miscellaneous)']"))).click();