-1

I have my simple selenium program that validate if the value search box in the google is equal to hello world but i got this error:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"name","selector":"q"}....

Here's my complete code

public class SimpleSelenium {

  WebDriver driver = null;

public static void main(String args[]) {

    SimpleSelenium ss = new SimpleSelenium();
    ss.openBrowserInChrome();
    ss.getPage();
    ss.listenForHelloWorld();
    ss.quitPage();

}

private void openBrowserInChrome(){

    System.setProperty("webdriver.chrome.driver", "C:/chromedriver.exe");
    driver = new ChromeDriver();

}

private void quitPage() {

    driver.quit();
}

private void getPage() {
    driver.get("http://www.google.com");

}

private void listenForHelloWorld() {

    WebElement searchField = driver.findElement(By.name("q"));
    int count = 1;
    while (count++ < 20) {

        if (searchField.getAttribute("value").equalsIgnoreCase("hello world")) {
            break;
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}




   }
iamsankalp89
  • 4,607
  • 2
  • 15
  • 36
Mr.Aw
  • 216
  • 3
  • 16

2 Answers2

0

Do you wait until the page is ready and element displayed? I've often got this error when the page is still loading. You could add something like

(MochaJS example, pretty much the same API for JAVA tests)

test.it('should check the field existence', function (done) {
  let field_by = By.id(ID_OF_THE_FIELD);
  driver.wait(until.elementLocated(field_by, 
  driver.wait(until.elementIsVisible(driver.findElement(field_by)), TIME_TO_WAIT_MS);
        done();
    });

You wait until the element is visible. If it failed, the timeout of TIME_TO_WAIT_MS will be raised.

gigouni
  • 11
  • 3
0

The google search bar will never have "hello world" in it because you haven't typed it in?

Also the search field value doesn't seem to update when you type in a search (if you inspect the element using the Console).

If your just learning I would just write a test like this and the click the search button, then confirm the "hello world" text in the search results:

    WebElement searchField = driver.findElement(By.name("q"))
    searchField.sendKeys("Hello World")
    //Add code to click search button
    //Add code to assert results on next page

Also I would completely change your listenForHelloWorld() method and use the built in WebDriver ExpectedConditions:

new WebDriverWait(driver, 10)
                .until(ExpectedConditions.textToBePresentInElement(searchField, "Hello World"))
Rushby
  • 869
  • 9
  • 18