1

I want to select the first option showing in an autocomplete text box. Below is the code which i tried but not getting the required output.

Code:

public void clickSublink() throws IOException, InterruptedException {   
    System.setProperty("webdriver.chrome.driver","F:\\Amitha\\chromedriver.exe");
    WebDriver dr=new ChromeDriver();
    dr.get("http://demoqa.com/autocomplete/");
    dr.findElement(By.xpath("//input[@id='tags']")).sendKeys("b");
    dr.findElement(By.xpath("//ul[@id='ui-id-1']//child::li")).click();
}
DebanjanB
  • 118,661
  • 30
  • 168
  • 217
amitha k
  • 13
  • 3

3 Answers3

1

To select the first option from the text box, you need to use elementToBeClickable() and you can use either of the following Locator Strategies:

  • cssSelector:

    driver.get("http://demoqa.com/autocomplete/");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("input.ui-autocomplete-input#tags"))).sendKeys("b");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.cssSelector("ul.ui-autocomplete>li>div"))).click();
    
  • xpath:

    driver.get("http://demoqa.com/autocomplete/");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@class='ui-autocomplete-input' and @id='tags']"))).sendKeys("b");
    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//ul[@class='ui-menu ui-widget ui-widget-content ui-autocomplete ui-front']/li/div"))).click();
    
DebanjanB
  • 118,661
  • 30
  • 168
  • 217
0

If you want to select only first option you can use keys class in selenium.Please find below code for the same.

public void clickSublink() throws IOException, InterruptedException {   
System.setProperty("webdriver.chrome.driver","F:\\Amitha\\chromedriver.exe");
WebDriver dr=new ChromeDriver();
dr.get("http://demoqa.com/autocomplete/");
dr.findElement(By.xpath("//input[@id='tags']")).sendKeys("b");
dr.findElement(By.xpath("//input[@id='tags']")).sendKeys(Keys.DOWN, Keys.ENTER);}
0

Another approach :

library (XML)
library(RCurl)
data=htmlParse("http://demoqa.com/autocomplete/")
result=xpathSApply(data,"normalize-space(substring-before(substring-after(//div[@class='demo-frame']//script[last()]/text(),'['),']'))")
reg=gsub('\"',"",result)
final=unlist(strsplit(reg,", "))

Produces :

[1] "ActionScript" "AppleScript"  "Asp"          "BASIC"        "C"            "C++"         
[7] "Clojure"      "COBOL"        "ColdFusion"   "Erlang"       "Fortran"      "Groovy"      
[13] "Haskell"      "Java"         "JavaScript"   "Lisp"         "Perl"         "PHP"         
[19] "Python"       "Ruby"         "Scala"        "Scheme"
DebanjanB
  • 118,661
  • 30
  • 168
  • 217
E.Wiest
  • 5,122
  • 2
  • 4
  • 11