【问题标题】:How to select the first auto suggestion using Selenium and Java如何使用 Selenium 和 Java 选择第一个自动建议
【发布时间】:2019-09-25 03:55:37
【问题描述】:

我正在输入要搜索的名称,然后显示自动建议,但我无法从自动建议中选择第一个选项。

这是带有 TestNG 插件的日食氧气

driver.findElement(By.className("searchfilter")).sendKeys("Abilify");// This is working But after that option selection is not working

driver.findElement(By.cssSelector(".list-group-item:first-child")).click(); // Issue is here

HTML代码:

<li class="list-group-item list-group-item-action py-3 tabindex fs-1-1 bg-offwhite" id="indexTab1" href="970-ABILIFY" name="ABILIFY - ARIPIPRAZOLE">ABILIFY - ARIPIPRAZOLE</li>

【问题讨论】:

  • 安必利-阿立哌唑

标签: java selenium-webdriver xpath css-selectors autosuggest


【解决方案1】:

1- 首先在搜索框中输入您的单词。

2- 然后等到您的搜索元素可见或可点击。

 WebDriverWait wait = new WebDriverWait(driver, milliseconds);
 wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//li[@id='indexTab1']"))));

3- 然后点击想要的元素

driver.findElement(By.xpath("//li[@id='indexTab1']")).click();

【讨论】:

    【解决方案2】:

    我认为,您的是单页应用程序。很可能是它的 Angular js 应用程序。这些 SPA 会根据您在下拉编辑框中键入的内容不断更新/显示下拉列表中的选项。

    请尝试以下代码,

    driver.findElement(By.className("searchfilter")).sendKeys("Abilify");

    driver.findElement(By.Xpath("//li[contains(text(), 'Abilify')]")) 。点击() ; // 注意:如果有多个匹配项,Selenium 总是对第一个元素起作用。

    你也可以像下面这样参数化你的选择值

    String temp="Abilify"; driver.findElement(By.className("searchfilter")).sendKeys(temp);

    driver.findElement(By.Xpath("//li[contains(text()," + temp +")]")).click() ;

    问候, 帕萨

    【讨论】:

      【解决方案3】:

      使用所需文本调用sendKeys() 后,选择第一个自动建议需要为visibilityOfElementLocated() 诱导WebDriverWait,您可以使用以下任一Locator Strategies

      • cssSelector:

        driver.findElement(By.className("searchfilter")).sendKeys("Abilify");
        new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("li.list-group-item-action[name='ABILIFY - ARIPIPRAZOLE'][href$='-ABILIFY']"))).click();
        
      • xpath:

        driver.findElement(By.className("searchfilter")).sendKeys("Abilify");
        new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//li[contains(@class, 'list-group-item-action') and @name='ABILIFY - ARIPIPRAZOLE'][contains(., 'ABILIFY - ARIPIPRAZOLE')]"))).click();
        

      【讨论】:

        猜你喜欢
        相关资源
        最近更新 更多
        热门标签