Google search button click with selenium

Viewed 4384

I am learning selenium but I can't seem to click the google search button with it. What I am trying:

        IWebDriver driver = new ChromeDriver();
        driver.Url = "https://google.com";
        IWebElement searchBar = driver.FindElement(By.Name("q"));
        searchBar.SendKeys("Hello world!");
        IWebElement searchButton = driver.FindElement(By.Name("btnK"));
        searchButton.Click();

It fills the search bar with hello world properly but an exception while clicking the button: OpenQA.Selenium.ElementNotInteractableException: 'element not interactable

3 Answers

As you are learning, I think it's a good exercise for you where you can use findElements and then interact with the list item(s).

I can give you the idea then you have to implement it by your self which will give you more information rather just getting the answer.

You have to use findElements rather findElement as there are 2 elements with the same exact name attribute value.

 driver.FindElements(By.Name("btnK")) 

This will give you list of elements. Then check the size it will be 2. Now click on the 2nd Element.

Or you can just use JavaScript to click on the searchButton from your original post.

The easiest would be just calling IWebElement.Submit() method like:

searchBar.Submit();

going forward I would recommend using Explicit Wait so you can ensure that the element is present in DOM and is clickable using WebDriverWait and ExpectedConditions classes combination:

driver.Navigate().GoToUrl("http://google.com");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement searchBar = wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("q")));
searchBar.SendKeys("Hello world!");
IWebElement searchButton = wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("btnK")));
searchButton.Click();
driver.Quit();

More information: How to use Selenium to test web applications using AJAX technology

Try using xpath

it worked for me

        string searchBox="/html/body/div/div[3]/form/div[2]/div/div[1]/div/div[1]/input";
        string searchBtn="/html/body/div/div[3]/form/div[2]/div/div[3]/center/input[1]";
        IWebDriver driver = new ChromeDriver();
        driver.Url = "https://google.com";
        IWebElement searchBar = driver.FindElement(By.Path(searchBox));
        searchBar.SendKeys("Hello world!");
        IWebElement searchButton = driver.FindElement(By.XPath(searchBtn));
        searchButton.Click();

Let me nkow if xpath doesn't work for you

Related