2016-02-19 85 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檢查複選框並在瀏覽器上執行它 –