我对一个公共网站进行了一些测试,看看是否可以发现一些不同 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());
以下是结果,显示 xPath 保持其自身状态,500 次迭代的所有时间均以秒为单位。
Safari 是迄今为止表现最不稳定的,每次测试运行的时间都奇怪地不同。
Princeton.edu 是一个相当普通的网页,具有相当简单的选择器,但似乎表明 xPath 并没有那么糟糕。在测试我的工作站点时,我发现了同样的事情。
对我在这里可能缺少什么有什么想法吗?
人们似乎懒惰地认为 Xpath 很慢,应该避免。当我采访一些人时,当他们说他们避免使用 Xpath 因为它又慢又脆弱时,我会感到畏缩。正如这里所示,速度不再是一个问题,xpath 的脆弱程度取决于编写它的人。在正确的场景中,Xpath 非常棒,实际上可以提高性能,因为它允许您在一个可能需要执行多个命令的命令中执行(例如,查找元素然后迭代子元素可以在一个 xpath 中执行)
哦,不要让我开始认为一个元素只有一个 Xpath 并且可以通过右键单击 firebug 找到它的人
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)