2016-02-19 59 views
1
access = 'Product Name' 
path = "//span[contains(text(), '#{access}')]/parent::*[1]/preceding-sibling::input[1]" 
jscript = <<EOF 
      function setCheckboxes(path){ 
var cbx = document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; 
cbx.click()}; 
setCheckboxes("#{path}"); 
EOF 
@browser.execute_script jscript 

当我运行该脚本,我得到一个错误:如何执行复杂的Javascript代码?

Selenium::WebDriver::Error::JavascriptError: JavaScript error 

没有问题的JavaScript或XPath。问题在于执行。 你能帮我解决什么问题吗?

+0

什么是完整的堆栈跟踪?实际上,这看起来像来自驱动程序中的错误。 1.使用$ DEBUG = true运行测试,然后粘贴executeScript的帖子和响应。 2.这是什么浏览器?它在其他浏览器上失败吗? 3.为什么你需要在Javascript中做到这一点?通常这是一个坏主意。 :) – titusfortner

+0

您好提示,它是在IE浏览器,我需要这样做,它要快得多,因为将有一个产品阵列(约400),并使用watir sept复选框是慢得多。 –

+0

在黑暗中拍摄,但我想知道它是否与'path'变量的插值有关(即'setCheckboxes(“#{path}”);')。根据['documentation'](http://ruby-doc.org/core-2.2.0/doc/syntax/literals_rdoc.html#label-Here+Documents),这里的文档允许插值。所以,可能不需要双引号。 – orde

回答

0

问题是,IE不支持XPath - 即不支持document.evaluate(请参阅MDN page)。

您将需要更改脚本,以便它使用IE支持的方法。一般有两种方法:

  1. 找到使用的Watir的元素,然后单击使用execute_script
  2. 找到并单击使用execute_script的元素的元素。

给定一个HTML页面400个复选框,如:

<input type="checkbox"> 
<label> 
    <span>Product Name</span> 
</label> 

我们可以以此为基准的各种方法:

def browser_setup 
    browser = Watir::Browser.new :ie 
    browser.goto 'file:///C:/test/page.htm' 
    browser 
end 

Benchmark.bm do |x| 
    x.report("Locate and click via standard methods:") do 
    browser = browser_setup 
    browser.checkboxes.each(&:click) 
    end 

    x.report("Locate via standard methods and click via script:") do 
    browser = browser_setup 
    browser.checkboxes.each do |checkbox| 
     browser.execute_script('arguments[0].click();', checkbox) 
    end 
    end 

    x.report("Locate and click via script:") do 
    access = 'Product Name' 
    check_all = %Q{ 
     all_spans = document.getElementsByTagName("span") 
     for (var i = 0, max = all_spans.length; i < max; i++){ 
     if (all_spans[i].innerText.indexOf("#{access}") > -1){ 
      var parent = all_spans[i].parentElement; 

      var preceding_sibling = parent.previousSibling; 
      while(preceding_sibling && preceding_sibling.nodeType != 1 && preceding_sibling.tagName != "input") { 
      preceding_sibling = preceding_sibling.previousSibling; 
      } 
     preceding_sibling.click(); 
     } 
     } 
    } 

    browser = browser_setup 
    browser.execute_script(check_all) 
    end 
end 

其中给出的结果:

              user  system  total  real 
Locate and click via standard methods:    0.109000 0.171000 0.280000 (207.682750) 
Locate via standard methods and click via script: 0.063000 0.031000 0.094000 (58.156400) 
Locate and click via script:       0.000000 0.000000 0.000000 ( 2.516400) 

从结果,我们可以看到这个大页面在你的时候表现的很慢只唱标准的Watir复选框方法。通过直接点击execute_script的元素,性能得到显着改善。当定位和点击通过execute_script完成时,检查几乎是瞬时的。

+0

这也是我的结论,我已经实现了使用javascript检查复选框并在浏览器上执行它 –