The below code is for searching a text automatically from the
auto suggest; mainly for a
list item.
driver.get("http://www.indiabookstore.net");
driver.findElement(By.id("searchBox")).sendKeys("Alche");
Thread.sleep(3000);
List <WebElement> listItems = driver.findElements(By.xpath("/html/body/div[4]/ul/li"));
listItems.get(0).click();
driver.findElement(By.id("searchButton")).click();
Note: We can also repalce the xpath locator,
By.xpath("/html/body/div[4]/ul/li") with
By.xpath("//div[4]/ul/li")
It's not a better way to use the above xpath locator; meanwhile these locators can be replaced with one of the following options (use csslocators for better solution).
List <WebElement> listItems = driver.findElements(By.xpath("//div[contains(@class,'acResults')]//li"));
List <WebElement> listItems = driver.findElements(By.xpath("//div[@class='acResults']//li"));
List <WebElement> listItems = driver.findElements(By.cssSelector(".acResults li"));
List<WebElement> link = driver.findElement(By.id("Element")).findElements(By.tagName("li"));
get(0) is the first option displayed on searching keywords
get(1) is the second option displayed on searching keywords
Anchor Tag :
HTML
<head>
<body id="data-search" class="hassidebar">
<ul id="material-result-list" style="top: 183px; left: 396.5px; width: 270px; display: block;">
<li>
<a>nitrate/0.2</a>
</li>
</ul>
CODE
Here, we need to click on specific anchor tag.
List<WebElement> listItems = driver.findElement(By.id("material-result-list")).findElements(By.tagName("a"));
listItems.get(2).click();