How to search for a keyword in google using Selenium Java?

SeleniumAutomation TestingTesting Tools

We can search for a keyword in Google using Selenium webdriver in Java.

In order, to perform a search, we have to first land on the Google page with the help of the get method.

Then identify the search edit box with the help of any of the locators like id, name, class, xpath, tagname, or css. Then enter the keyword in the search box with the help of the sendKeys method.

Finally, perform the keyword search by simulating ENTER keypress. This is done by using the sendKeys method and passing the parameter Keys.ENTER or Keys.RETURN.

Syntax

WebElement r = driver.findElement(By.className("q"));
r.sendKeys("Cypress");
r.sendKeys(Keys.RETURN);

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Keys;
public class KeyWrdSearch{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver",
         "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      //implicit wait
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      //URL launch
      driver.get("https://www.google.com/");
      //identify element
      WebElement r = driver.findElement(By.name("q"));
      r.sendKeys("Cypress");
      // press ENTER
      r.sendKeys(Keys.RETURN);
   }
}

Output

raja
Published on 08-Apr-2021 07:39:54
Advertisements