0
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.setProperty("webdriver.gecko.driver", "F:\\3rd year\\IS 3103\\New folder (2)\\geckodriver.exe");
        WebDriver objDriver= new FirefoxDriver();
        objDriver.get("http://www.google.com");
        objDriver.findElement(By.xpath("/html/body/div/div[3]/form/div[2]/div[1]/div[1]/div/div[2]/input")).sendKeys("GMAIL", Keys.ENTER);
        objDriver.findElement(By.xpath("/html/body/div[6]/div[2]/div[9]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div[1]/a/h3")).click();;

    }

}

This is the code I wrote. I want to write a selenium java code to search for GMAIL in google and go to the appropriate result by clicking on it. It does not execute after getting the search result and following error comes.

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: /html/body/div[6]/div[2]/div[9]/div[1]/div[2]/div/div[2]/div[2]/div/div/div[1]/div/div[1]/a/h3

Lak
  • 1
  • 3

1 Answers1

0

You cant hardcode google page because google elements are updating day by day

Following code is open google and type "testing" and store all results.finally click "testing types"

public class GooglesearchTests {

public static void main(String[] args) throws Exception {
    System.setProperty("webdriver.chrome.driver", "C:\\Users\\User\\Downloads\\chromedriver83\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();
    driver.get("https://www.google.com/");
    driver.findElement(By.name("q")).sendKeys("Testing");
    Thread.sleep(Long.parseLong("1000"));
    List<WebElement> LIST = driver.findElements(By.xpath("//ul[@role='listbox']//li/descendant::div[@class='sbl1']"));
    System.out.println(LIST.size());


    for (int i = 0; i < LIST.size(); i++)
    {
        //System.out.println(LIST.get(i).getText());
        if (LIST.get(i).getText().contains("testing types"))
        {
            LIST.get(i).click();
            break;
        }
    }
}

}

Justin Lambert
  • 940
  • 1
  • 7
  • 13