无法使用Selenium Java单击指定的li元素

问题描述 投票:0回答:1

我需要使用下拉列表单击指定的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();
                //...
            }
        }

条件不会被忽略并成功通过,但是程序不会单击按钮,并且列表已关闭。

有人可以建议我在这里解决问题吗?

java selenium xpath webdriverwait expected-condition
1个回答
0
投票

首先,要显示li,请单击此元素:

driver.findElement(By.className("dropdown")).click();

第二,您需要在循环中添加break语句:

for (WebElement opt : opts) {
    if(opt.getText().equals(textInput)){
        opt.click();
        //here
        break;
    }
}

成功单击所需的页面后,您已切换到另一页,因此此后的li元素不再存在。因此,您需要一个break语句。


0
投票
从下拉列表中的

到文本为[[农业和生物科学(杂项)的元素上的click(),您需要为elementToBeClickable()引入WebDriverWait,并且可以使用以下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 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();

  • 浏览器快照:
  • scimagojr

    © www.soinside.com 2019 - 2024. All rights reserved.