0

I am trying to open google.com first then type "selenium testing".

I only wanted to use className for webdriver using eclipse but I am getting the following error.

Exception in thread "main" 
   org.openqa.selenium.NoSuchElementException: Unable to locate element: 
   {"method":"class name","selector":"Tg7LZd"}
   Command duration or timeout: 37 milliseconds

Here is my code:

package coreJava;

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

public class Training1 {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
        driver.findElement(By.className("gLFyf")).sendKeys("selenium testing");     
        driver.findElement(By.className("Tg7LZd")).click();
    }
}

How do I fix this?

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
dan fan
  • 29
  • 3

2 Answers2

1

This error message...

org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"class name","selector":"Tg7LZd"}

...implies that the GeckoDriver was unable to find any element as per the Locator Strategy you have used.

Your main issue is the classNames you have used are based on JavaScript and are generated dynamically which we can't guess before they are generated. As an alternative you can use the following solution:

package coreJava;

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

public class Training1 {
    public static void main(String[] args) {
        WebDriver driver = new FirefoxDriver();
        driver.get("http://www.google.com");
        WebElement myElement = driver.findElement(By.name("q"));  
        myElement.sendKeys("selenium testing");
        myElement.submit();
    }
}
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0
System.setProperty("webdriver.gecko.driver", "geckodriver");
FirefoxDriver driver = new FirefoxDriver();

driver.get("https://google.com");
Thread.sleep(3);

driver.findElement(By.className("gsfi")).sendKeys("selenium testing");
Thread.sleep(3);

driver.findElement(By.className("sbqs_c")).click();
Thread.sleep(3);

driver.close(); 

This is working code

. These will open the google chrome and then write "selenium testing" in search box and then search it using the class.

Hiten
  • 724
  • 1
  • 8
  • 23