-1

My test steps are-

  • a) go to google.com
  • b) in the search box start typing a keyword example "IBM"
  • c) google displays all the matching results
  • d) Get the count of matching results in a List of strings.

for (a), (b) I have:-

System.setProperty("webdriver.chrome.driver", "C:\\Work\\chromedriver.exe");
        WebDriver driver = new ChromeDriver();
        driver.get("http://www.google.com");
        WebElement element = driver.findElement(By.name("q"));
        element.sendKeys("IBM");

The Question is how I do (d)?

3 Answers 3

2

I have checked the first two results and the locator is same.

So you can create a List of these elements by using FindElements method.

And then put logic to create list of only matching Strings out of it.

0

Hope this help you:-

System.setProperty("webdriver.chrome.driver", "C:\\Work\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
driver.manage().window().maximize();
WebElement element = driver.findElement(By.name("q"));
element.sendKeys("IBM");
Thread.sleep(1000);
WebElement matchingResult= driver.findElement(By.xpath(".//div[@class='aajZCb']/ul"));
List<WebElement> listResult= matchingResult.findElements(By.xpath("//li/div/div[@class='sbtc']"));
System.out.println(listResult.size());
//if you want to print matching results
     for(WebElement results: listResult)
       {
         String value= results.getText();
         System.out.println(value);
       }     
3
  • Thank you for the code but what I want is a bit different Commented Jun 22, 2019 at 11:57
  • when I type IBM before I hit enter I want to get the list of matches. when I type IBM in the search box it comes up with IBM, IBM stock, IBM Watson, IBM computer and IBM as the possible hints for the keyword. What is the way to capture all those possible hints. Thank you Commented Jun 22, 2019 at 12:00
  • Thank you for telling us @CuriousCoder, i have edited the code, hope this help you. Commented Jun 24, 2019 at 6:02
0

While I didn't search for IBM I have done something similar with the a recipe search engine.

List<WebElement> searchList = new ArrayList<>(); //creates a list of webelements
    
    //grabbing the search results with a tag
    
    searchList.addAll(driver.findElements(By.tagName("a"))); 
    
    

    
    //Checking size of the arraylist
    
    System.out.println(searchList.size());
    
    
    

While as I said that it is not from google I do not know the exact tag you will be looking for this should be a valid answer. Once you have the list of WebElements it should show you the size of the list. If all you want is the umber of items.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.