Search code examples
javaseleniumautocompleteinputbox

How to fill in an autocomplete inputbox using Selenium? (Why an automated input does not load autocomplete options BUT a manual input does?)


The following code tests an autocomlete box of a webpage:

public class Test {

    public static void main(String[] args) throws InterruptedException {
        System.setProperty("webdriver.chrome.driver","chromedriver\\chromedriver.exe");     
        WebDriver driver = new ChromeDriver();
        driver.get("http://www..............com"); 
        driver.switchTo().frame("mainFrame");

        WebDriverWait waitst = new WebDriverWait(driver, 120);
        waitst.until(ExpectedConditions.visibilityOfElementLocated(By.name("sourceTitle")));

        WebElement sourceTitle = driver.findElement(By.name("sourceTitle"));
        WebElement small = driver.findElement(By.cssSelector("li#nameExampleSection label + small"));
        sourceTitle.sendKeys("Times"); 
        Thread.sleep(5000);
        Actions actions = new Actions(driver);
        actions.click(small).perform();

    }

}

Why doesn't the autosuggest box load? IMPORTANT: try to type in "..........." manually ... the autocomplete box will load perfectly fine!!! So, why does not cssSelector work, why doesn't it load the autocomplete box?

How come an automated input does not allow for autocomplete options BUT a manual input does???

PS: I also tried fireEvent, sendKeys but nothing works.


Solution

  • I tried your code, it does exactly what the manual walkthough does. "Associated Press, The" returns only a "No Match, please try sources". In your code you then try to click on the next form list item, not the results popup. The autosuggest popup is dynamically populated at the top of your html page positioned under the input form. The following code does select the first option on your drop down.

    @Test
    public void test() throws InterruptedException {
            WebDriver driver = new ChromeDriver();
            driver.get("http://www.lexisnexis.com/hottopics/lnacademic/?verb=sf&sfi=AC00NBGenSrch"); 
            driver.switchTo().frame("mainFrame");
    
            WebDriverWait waitst = new WebDriverWait(driver, 0);
            waitst.until(ExpectedConditions.visibilityOfElementLocated(By.name("sourceTitle")));
    
            WebElement sourceTitle = driver.findElement(By.name("sourceTitle"));
            sourceTitle.sendKeys("Times"); 
            Thread.sleep(5000);
            WebElement firstItem = driver.findElement(By.xpath("//*[@class='auto_suggest']/*[@class='title_item']"));
            firstItem.click();
    }