How to locate search links in google in Selenium for testing

Rishi picture Rishi · May 11, 2013 · Viewed 9.1k times · Source

I am trying to search Google for Selenium, then run down the list of links by clicking each one, printing the page title, then navigating back.

List<WebElement> linkElements = driver.findElements( **<insert code here>** );

for(WebElement elem: linkElements)
{
    String text = elem.getText();
    driver.findElement(By.linkText(text)).click();
    System.out.println("Title of link\t:\t" + driver.getTitle());
    driver.navigate().back();
}

To find the elements, I have tried By.tagName("a") which doesn't work because it gets ALL the links, not just the search ones. Using Firebug, I see that each search link has a class of r used on the header h3, and the a tag nested inside it.

See the following:

<h3 class="r">
<a href="/url sa=t&amp;rct=j&amp;q=selenium&amp;source=web&amp;cd=1&amp;cad=rja&amp;ved=0CC8QFjAA&amp;url=http%3A%2F%2Fseleniumhq.org%2F&amp;ei=y4eNUYiIGuS7iwL-r4DADA&amp;usg=AFQjCNHCelhj_BWssRX2H0HZCcPqhgBrRg&amp;sig2=WBhmm65gCH7RQxIv9vgrug&amp;bvm=bv.46340616,d.cGE" onmousedown="return rwt(this,'','','','1','AFQjCNHCelhj_BWssRX2H0HZCcPqhgBrRg','WBhmm65gCH7RQxIv9vgrug','0CC8QFjAA','','',event)"><em>Selenium</em> - Web Browser Automation
</a></h3>

What code can I insert to make this work?

Answer

Omkar picture Omkar · May 11, 2013

Try below New Code

    WebDriver driver;
    driver = new FirefoxDriver();
    driver.get("http://www.google.com");
    driver.findElement(By.id("gbqfq")).sendKeys("Selenium");
    Thread.sleep(1500L);
    driver.findElement(By.id("gbqfb")).click();
    Thread.sleep(1500L);
    List<WebElement> linkElements = driver.findElements(By.xpath("//h3[@class='r']/a"));
     for(int i=0;i<=linkElements.size();i++)
        {
            String text = linkElements.get(i).getText();
            driver.findElement(By.linkText(text)).click();
            Thread.sleep(2000L);
            System.out.println("Title of link\t:\t" + driver.getTitle());
            Thread.sleep(2000L);
            driver.navigate().back();
            linkElements = driver.findElements(By.xpath("//h3[@class='r']/a"));

        }