Why doesn't Selenium find element by xpath?

1.6k Views Asked by At

When I run the following program, why is '0' printed to the console? I expected '1' to be printed since I expected the findElements() method to find a link using the xpath. Is the xpath expression incorrect? I got the expression using Firefox, Firebug, and Firepath, by selecting the link element and copying the given xpath.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.By;
import java.util.List;

public class SeleniumSearch {
    static WebDriver driver = new FirefoxDriver();

    public static void main(String[] args) {

        try {
            driver.get("http://www.google.co.uk/");
            submitSearch("selenium");
            getHit();
        }
        finally {
            driver.close();
        }
    }

    static void submitSearch(String search) {
        WebElement searchBox = driver.findElement(By.name("q"));
        searchBox.sendKeys(search);
        searchBox.submit();
    }

    static void getHit() {
        List<WebElement> hits = driver.findElements(By.xpath("html/body/div[5]/div[4]/div[9]/div[1]/div[3]/div/div[3]/div[2]/div/div/div/div[2]/div[1]/div/h3/a"));
        System.out.println(hits.size());
    }
}

Screen shot of the xpath given by Firepath

4

There are 4 best solutions below

1
Leon Barkan On
xpath("html/body/div[5]/div[4]/div[9]/div[1]/div[3]/div/div[3]/div[2]/div/div/div/div[2]/div[1]/div/h3/a")

That's wrong work with xpath, one little change on website and your code wouldn't work! try to do it more dynamic find the closest id or tag name and continue from there, can you share your html source?

0
Nidhi Jhunjhunwala On

Try putting the following as xpath instead of the actual path: //*[@id="rso"]/div[2]/div[1]/div/h3/a

0
stan On

I would use a simple xpath like html/body//h3/a. You can also use FirePath extension of FireBug to build and evaluate xpaths.

1
Richard On

Simplest xpath I could come up with for first link in google search:

(//h3/a)[1]