When working with Selenium web testing, there are a few ways to identify WebElements.
In my experience, I have used the following selectors:
Just for s&gs...
I timed each of the identifier methods finding the div above five separate times and averaged the time taken to find the element.
WebDriver driver = new FirefoxDriver();
driver.get("file:///div.html");
long starttime = System.currentTimeMillis();
//driver.findElement(By.className("class"));
//driver.findElement(By.cssSelector("html body div"));
//driver.findElement(By.id("id"));
//driver.findElement(By.name("name"));
//driver.findElement(By.tagName("div"));
//driver.findElement(By.xpath("/html/body/div"));
long stoptime = System.currentTimeMillis();
System.out.println(stoptime-starttime + " milliseconds");
driver.quit();
They are sorted below by average run time..
After reading @JeffC 's answer I decided to compare By.cssSelector() with classname, tagname, and id as the search terms. Again, results are below..
WebDriver driver = new FirefoxDriver();
driver.get("file:///div.html");
long starttime = System.currentTimeMillis();
//driver.findElement(By.cssSelector(".class"));
//driver.findElement(By.className("class"));
//driver.findElement(By.cssSelector("#id"));
//driver.findElement(By.id("id"));
//driver.findElement(By.cssSelector("div"));
//driver.findElement(By.tagName("div"));
long stoptime = System.currentTimeMillis();
System.out.println(stoptime-starttime + " milliseconds");
driver.quit();
By.cssSelector(".class"): (327ms + 165ms + 166ms + 282ms + 55ms) / 5 = ~199msBy.className("class"): (338ms + 801ms + 529ms + 804ms + 281ms) / 5 = ~550msBy.cssSelector("#id"): (58ms + 818ms + 261ms + 51ms + 72ms) / 5 = ~252msBy.id("id") - (820ms + 543ms + 112ms + 434ms + 738ms) / 5 = ~529msBy.cssSelector("div"): (594ms + 845ms + 455ms + 369ms + 173ms) / 5 = ~487msBy.tagName("div"): (825ms + 843ms + 715ms + 629ms + 1008ms) / 5 = ~804msFrom this, it seems like you should use css selectors for just about everything you can!