Selenium元素选择器 - 我认为xPath是最慢的?

Jac*_*eks 10 selenium xpath webdriver css-selectors

我对一个公共网站进行了一些测试,看看我是否能找到一些不同的Selenium CSS选择器的性能差异.我跑了一个有五个节点的集线器; mac/chrome/local,mac/safari/local,mac/ff/local,win7/ie9/localVM和win8/ie10,localVM.测试全部并行运行,试图模拟我通常如何运行它们.我惊讶地发现xPath选择器并没有成为我所期待的魔鬼.也许我的测试有点时髦吗?有人有任何见解吗?

这是测试代码......

    int cycles = 500;
int yVal = 0;

getPage(“http://www.princeton.edu");

/* try an element that does not have an id*/
startStopwatch();
for (int i = 0; i < cycles; i++)
    yVal = driver.findElementByCssSelector("a[href='/main/news/events/']").getLocation().y;
print("By CSS: " + elapsedSeconds());

startStopwatch();
for (int i = 0; i < cycles; i++)
    yVal = driver.findElementByCssSelector("div[id='events'] a[href='/main/news/events/']").getLocation().y;
print("By CSS using id: " + elapsedSeconds());


startStopwatch();
for (int i = 0; i < cycles; i++)
    yVal = driver.findElementByXPath("//a[@href=\'/main/news/events/']").getLocation().y;
print("By xPath: " + elapsedSeconds());

/* try an element with an id */
//by id
startStopwatch();
for (int i = 0; i < cycles; i++)
    yVal = driver.findElementById("events").getLocation().y;
print("By Id: " + elapsedSeconds());

//by CSS
startStopwatch();
for (int i = 0; i < cycles; i++)
    yVal = driver.findElementByCssSelector("div[id='events']").getLocation().y;
print("By CSS: " + elapsedSeconds());

// an unnecessarily long xPath expression
startStopwatch();
for (int i = 0; i < cycles; i++)
    yVal = driver.findElementByXPath("//span[text()='News at Princeton']/ancestor::div[1]/following-sibling::div[1]").getLocation().y;
print("By longer xPath: " + elapsedSeconds());

// somewhat shorter xPath
startStopwatch();
for (int i = 0; i < cycles; i++)
    yVal = driver.findElementByXPath("//span[text()='Featured Events']/ancestor::div[1]").getLocation().y;
print("By shorter xPath: " + elapsedSeconds());
Run Code Online (Sandbox Code Playgroud)

以下是结果,显示xPath保持自己的状态,所有时间都是以秒为单位进行500次迭代.

硒选择器比较表

Safari是迄今为止最不稳定的表演者,每次试播都有不同的时间.

princeton.edu是一个非常普遍的网页,有相当容易的选择器,但似乎暗示xPath并没有那么糟糕.在测试我的工作网站时,我发现了同样的事情.

我对这里可能缺少的任何想法?

Rob*_*ham 7

人们似乎懒得假设Xpath很慢,应该避免.当我采访的时候,当他们说他们避开Xpath时我会畏缩,因为它缓慢而脆弱.如图所示,速度不再是一个问题,xpath只是写它的人那么脆弱.在正确的场景中,Xpath非常棒,并且实际上可以提高性能,因为它允许您在一个可能已经执行多个命令的命令中执行(例如,查找元素然后遍历子元素可以在一个xpath中执行)

哦,不要让我开始认为一个元素只有一个Xpath的人,并且通过右击firebug找到它

  • 顺便说一句,我选择CSS选择器作为我的第一选择,但很高兴在有意义的时候使用Xpath.我觉得CSS选择器通常比Xpath更具可读性,但是在需要时我很乐意使用XPath (4认同)
  • 每当存在CSS选择器等价物时,我仍然会使用CSS选择器,因为它更短.).`[id ^ ='foo']> [class*='something'] [name $ ='big']`比其等效的XPath更易于维护. (2认同)