What is the most efficient selector to use with findElement()?

前端 未结 4 1419
陌清茗
陌清茗 2020-12-16 05:26

When working with Selenium web testing, there are a few ways to identify WebElements.

In my experience, I have used the following selectors:

  • Cl
4条回答
  •  天命终不由人
    2020-12-16 06:17

    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..

    • CssSelector: (796ms + 430ms + 258ms + 408ms + 694ms) / 5 = ~517.2ms
    • ClassName: (670ms + 453ms + 812ms + 415ms + 474ms) / 5 = ~564.8ms
    • Name: (342ms + 901ms + 542ms + 847ms + 393ms) / 5 = ~605ms
    • ID: (888ms + 700ms + 431ms + 550ms + 501ms) / 5 = ~614ms
    • Xpath: (835ms + 770ms + 415ms + 491ms + 852ms) / 5 = ~672.6ms
    • TagName: (998ms + 832ms + 1278ms + 227ms + 648ms) / 5 = ~796.6ms

    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 = ~199ms
    • By.className("class"): (338ms + 801ms + 529ms + 804ms + 281ms) / 5 = ~550ms
    • By.cssSelector("#id"): (58ms + 818ms + 261ms + 51ms + 72ms) / 5 = ~252ms
    • By.id("id") - (820ms + 543ms + 112ms + 434ms + 738ms) / 5 = ~529ms
    • By.cssSelector("div"): (594ms + 845ms + 455ms + 369ms + 173ms) / 5 = ~487ms
    • By.tagName("div"): (825ms + 843ms + 715ms + 629ms + 1008ms) / 5 = ~804ms

    From this, it seems like you should use css selectors for just about everything you can!

提交回复
热议问题