2010-08-19 57 views
3

評估長xpath所需時間與短xpath相比有什麼重大區別?例子:
Ex。 是否有使用 By.id("id1")

By.Xpath("//*[@id='id1']")Webdriver Xpath性能

回答

13

我很高興你問之間
/div[@id = 'id1']/label[contains(text(), 'Hello')/../../descendant::input

//input

關於什麼區別之間的性能差異,我找到了答案令人吃驚。

  • 短XPath是比長的XPath快,但不是很多
  • 在Firefox按名稱搜索是比長的XPath,但爲短的XPath(有時更快)熱死
  • 在Internet Explorer更快,通過。名稱是遠比XPath的

這似乎在指導西蒙·斯圖爾特一直給人重新面對飛:IE瀏覽器的性能的XPath,所以我把它當作一粒鹽,但在下面的代碼中,它非常一致。

我寫了一個快速測試來說明這一點。它看起來在搜索框上的谷歌

package com.PeterNewhook; 

import org.openqa.selenium.By; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.firefox.FirefoxDriver; 
import org.openqa.selenium.ie.InternetExplorerDriver; 

public class FooTest { 

public static void main(String[] args) { 
    long start; 
    long end; 
    WebDriver driver; 
    String longXpath = "/html/body/span[@id='main']/center/span[@id='body']/center/form/table/tbody/tr/td[2]/div[@class='ds']/input[@name='q']"; 
    String shortXpath = "//input[@name='q']"; 
    String elementId = "q"; 

    System.out.println("Using Firefox driver."); 
    driver = new FirefoxDriver(); 
    driver.get("http://google.com"); 
    start = System.nanoTime(); 
    driver.findElement(By.xpath(longXpath)); 
    end = System.nanoTime()-start; 
    System.out.println("The long XPath lookup took " + (double)end/1000000000.0 + " seconds."); 
    start = System.nanoTime(); 
    driver.findElement(By.xpath(shortXpath)); 
    end = System.nanoTime() - start; 
    System.out.println("The short XPath lookup took " + (double)end/1000000000.0 + " seconds."); 
    start = System.nanoTime(); 
    driver.findElement(By.name(elementId)); 
    end = System.nanoTime() - start; 
    System.out.println("The By.name lookup took " + (double)end/1000000000.0 + " seconds."); 
    driver.close(); 

    System.out.println("\nUsing Internet Explorer driver.");   
    driver = new InternetExplorerDriver(); 
    driver.get("http://google.com"); 
    start = System.nanoTime(); 
    driver.findElement(By.xpath(longXpath)); 
    end = System.nanoTime()-start; 
    System.out.println("The long XPath lookup took " + (double)end/1000000000.0 + " seconds."); 
    start = System.nanoTime(); 
    driver.findElement(By.xpath(shortXpath)); 
    end = System.nanoTime() - start; 
    System.out.println("The short XPath lookup took " + (double)end/1000000000.0 + " seconds."); 
    start = System.nanoTime(); 
    driver.findElement(By.name(elementId)); 
    end = System.nanoTime() - start; 
    System.out.println("The By.name lookup took " + (double)end/1000000000.0 + " seconds."); 
    driver.close(); 
} 
} 

這使輸出:

使用Firefox的驅動程序。
長XPath查找耗時0.13667022秒。
簡短的XPath查找花費了0.024628577秒。
By.name查找花費了0.025209911秒。

使用Internet Explorer驅動程序。
長XPath查找耗時0.196125248秒。
簡短的XPath查找耗時0.164044262秒。
By.name查找花費了1.005109964秒。