auto suggestive dropdown selenium webdriver – Practice question 1

By | April 19, 2019

Topic: How to select an option from auto suggestive dropdown in a website.

Below code is the solution for the 1st question present in the page.

package com;
import static org.testng.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AutoSuggestionDropdown {
static WebDriver driver = null;
public static void main(String[] args) throws Exception {

AutoSuggestionDropdown auto = new AutoSuggestionDropdown();
auto.suggestions();
auto.closeBrowser();

}

public void suggestions() throws Exception{
System.setProperty(“webdriver.chrome.driver”, “C:\\chromedriver_win32\\chromedriver.exe”);
driver=new ChromeDriver();
driver.get(“https://global.shopbakerhughes.com/”);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
Thread.sleep(2000);
driver.findElement(By.xpath(“//input[@id=’search’]”)).sendKeys(“drill”);
driver.findElement(By.xpath(“//input[@id=’search’]”)).sendKeys(Keys.DOWN);

// It doesn’t print anything, because text in the search bar is invisible until we select it.

String text = driver.findElement(By.xpath(“//input[@id=’search’]”)).getText();
System.out.println(“Text is “+text);
Thread.sleep(2000);

JavascriptExecutor js = (JavascriptExecutor)driver;
String str = “return document.getElementById(\”search\”).value;”;
String item = (String) js.executeScript(str);
System.out.println(item);
int i=0;
while(!item.contains(“drilling fluid”)){
i++;
driver.findElement(By.xpath(“//input[@id=’search’]”)).sendKeys(Keys.DOWN);
Thread.sleep(1000);
item = (String) js.executeScript(str);
System.out.println(item);
if(i>15){
break;
}
}
if(i>15){
System.out.println(“Item not found.”);
fail(“Desired item not found.”);
}else{
System.out.println(“Desire item found.”);
}
driver.findElement(By.xpath(“//input[@id=’search’]”)).sendKeys(Keys.TAB);
driver.findElement(By.xpath(“//button[@title=’Search’]”)).click();

}

public void closeBrowser(){
driver.close();
}

}

Output:

Text is
drill
drill bits
drill bit
drill bits 8.5
drilling tools
drill
drilling fluid
Drill Pipe Float Valve – 1F/2R – Rubber Repair Kit
Drill bit 12 1/4
drilling additives
drill bit 81/2
Drilling heads
DRILL PIPE, MODEL G, STL IRON RUBBER, 4-1/2 INCH
drill bits
drill bit
drill bits 8.5
drilling tools
Item not found.



Tags: selenium webdriver, selenium qa testing, selenium tutorials, selenium xpath, python testing, selenium framework, free selenium tutorials, select in selenium, mouse hover in selenium, how to select dropdown in selenium

Leave a Reply

Your email address will not be published. Required fields are marked *