如何在使用JavaScript的Selenium RC中使用xpath?

7

我正在使用Selenium RC和IE 6,XPath定位器非常缓慢。因此,我正在尝试查看javascript-xpath是否可以加速操作。

但是,我找不到足够/清晰的文档来了解如何使用本地xpath库。

我正在执行以下操作:

protected void startSelenium (String testServer, String appName, String testInBrowser){
    selenium = new DefaultSelenium("localhost", 4444, "*" +testInBrowser, testServer+ "/"+ appName + "/");
    echo("selenium instance created:"+selenium.getClass());
    selenium.start();
    echo("selenium instance started..." + testServer + "/" + appName +"/");

    selenium.runScript("lib/javascript-xpath-latest-cmp.js");
    selenium.useXpathLibrary("javascript-xpath");
    selenium.allowNativeXpath("true");
}

这会提高XPath定位器的速度,但改进并不一致。在某些运行中,定位器所需的时间减半;而有时则会随机变高。

我是否遗漏了任何配置步骤?如果有人成功过,请分享他们的看法和方法。

谢谢, 尼尔马尔

解决方案:

protected void startSelenium (String testServer, String appName, String testInBrowser){
    selenium = new DefaultSelenium("localhost", 4444, "*" +testInBrowser, testServer+ "/"+ appName + "/");
    echo("selenium instance created:"+selenium.getClass());
    selenium.start();
    echo("selenium instance started..." + testServer + "/" + appName +"/");

    selenium.useXpathLibrary("javascript-xpath");
}
2个回答

4

我自己实现了这个功能,只需要使用selenium.useXpathLibrary("javascript-xpath")。在我的测试中,IE 8上的Javascript xpath速度约为普通xpath的7倍。虽然我们只在IE上使用它,但我还没有在其他浏览器上进行过测试。


嗨,丹, 如果我们没有明确添加脚本,引擎从哪里来?? Selenium已经包含了这个js吗?我找不到任何证据。 - Nirmal Patel
如果您查看Selenium源代码,您会发现javascript-xpath-0.1.11.js包含在common\src\js\core\xpath中,因此我认为它是从那里提取的。某些东西导致我的测试速度提高了7倍。=) - Dan at Demand

0

我从未这样做过,但我认为你可能需要做类似的事情

//Add the library to the page since runScript just does an eval on the JS
selenium.runScript("document.body.append(document.createElement('script')).src = 'path/to/lib');"); 
selenium.useXpathLibrary("javascript-xpath");
selenium.allowNativeXpath("true");

您需要将库添加到页面中,然后加载它。

但是,我建议使用CSS选择器而不是XPath选择器,因为在Selenium中它们要快得多。您可以在这里看到如何使用不同的定位策略。我已经看到测试速度比原始XPath快至少两倍。


我目前正在使用CSS选择器...但它们有点复杂,而且在与IE一起使用时会出现更多问题。我正在探索javascript-xpath提供的速度改进,看看它们是否与CSS选择器相比。 - Nirmal Patel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接