[java] Selenium webdriver click google search

I'm searching text "Cheese!" on google homepage and unsure how can I can click on the searched links after pressing the search button. For example I wanted to click the third link from top on search page then how can I find identify the link and click on it. My code so far:

package mypackage;

import org.openqa.selenium.By; 

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.chrome.ChromeDriver; 
import org.openqa.selenium.support.ui.WebDriverWait;

public class myclass {

    public static void main(String[] args) {

        System.setProperty("webdriver.chrome.driver", "C:\\selenium-java-2.35.0\\chromedriver_win32_2.2\\chromedriver.exe");

         WebDriver driver = new ChromeDriver(); 
         driver.get("http://www.google.com"); 
         WebElement element = driver.findElement(By.name("q"));
         element.sendKeys("Cheese!");
         element.submit();

         //driver.close();
    }



}

This question is related to java selenium

The answer is


public class GoogleSearch {

    public static void main(String[] args) {

        WebDriver driver=new FirefoxDriver();
        driver.get("http://www.google.com");
        driver.findElement(By.xpath("//input[@type='text']")).sendKeys("Cheese");   
        driver.findElement(By.xpath("//button[@name='btnG']")).click();
        driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); 
        driver.findElement(By.xpath("(//h3[@class='r']/a)[3]")).click();
        driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); 
    }
}

Most of the answers on this page are outdated.
Here's an updated python version to search google and get all results href's:

import urllib.parse
import re
from selenium import webdriver
driver.get("https://google.com/")
q = driver.find_element_by_name('q')
q.send_keys("always look on the bright side of life monty python")
q.submit();
sleep(1)
links= driver.find_elements_by_xpath("//h3[@class='r']//a")
for link in links:
    url = urllib.parse.unquote(webElement.get_attribute("href")) # decode the url
    url = re.sub("^.*?(?:url\?q=)(.*?)&sa.*", r"\1", url, 0, re.IGNORECASE) # get the clean url

Please note that the element id/name/class (@class='r') ** will change depending on the user agent**.
The above code used PhantomJS default user agent.


@Test
public void google_Search()
{
    WebDriver driver;
    driver = new FirefoxDriver();
    driver.get("http://www.google.com");
    driver.manage().window().maximize();

    WebElement element = driver.findElement(By.name("q"));
    element.sendKeys("Cheese!\n");
    element.submit();

    //Wait until the google page shows the result
    WebElement myDynamicElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(By.id("resultStats")));

    List<WebElement> findElements = driver.findElements(By.xpath("//*[@id='rso']//h3/a"));

    //Get the url of third link and navigate to it
    String third_link = findElements.get(2).getAttribute("href");
    driver.navigate().to(third_link);
}

There would be multiple ways to find an element (in your case the third Google Search result).

One of the ways would be using Xpath

#For the 3rd Link
driver.findElement(By.xpath(".//*[@id='rso']/li[3]/div/h3/a")).click();
#For the 1st Link
driver.findElement(By.xpath(".//*[@id='rso']/li[2]/div/h3/a")).click();
#For the 2nd Link
driver.findElement(By.xpath(".//*[@id='rso']/li[1]/div/h3/a")).click();

The other options are

By.ByClassName 
By.ByCssSelector 
By.ById
By.ByLinkText
By.ByName
By.ByPartialLinkText 
By.ByTagName 

To better understand each one of them, you should try learning Selenium on something simpler than the Google Search Result page.

Example - http://www.google.com/intl/gu/contact/

To Interact with the Text input field with the placeholder "How can we help? Ask here." You could do it this way -

# By.ByClassName 
driver.findElement(By.ClassName("searchbox")).sendKeys("Hey!");
# By.ByCssSelector 
driver.findElement(By.CssSelector(".searchbox")).sendKeys("Hey!");
# By.ById
driver.findElement(By.Id("query")).sendKeys("Hey!");
# By.ByName
driver.findElement(By.Name("query")).sendKeys("Hey!");
# By.ByXpath
driver.findElement(By.xpath(".//*[@id='query']")).sendKeys("Hey!");

Simple Xpath for locating Google search box is: Xpath=//span[text()='Google Search']


Based on quick inspection of google web, this would be CSS path to links in page list

ol[id="rso"] h3[class="r"] a

So you should do something like

String path = "ol[id='rso'] h3[class='r'] a";
driver.findElements(By.cssSelector(path)).get(2).click();

However you could also use xpath which is not really recommended as a best practice and also JQuery locators but I am not sure if you can use them aynywhere else except inArquillian Graphene


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?