2011-06-11 57 views
1

我想在与红宝石硒webdriver的jquery定位器。这里是我的代码:在硒webdriver处理jQuery的定位器,红宝石

require "selenium-webdriver" 

driver = Selenium::WebDriver.for(:remote, :desired_capabilities => :firefox) 
driver.navigate.to("http://google.com") 

# input.lst is the search input text in google.com 
selector = "input.lst" 

# get element from the locator 
element = driver.execute_script("return $(#{selector}).get(0);") 

# type "google" into the input text 
element.send_keys "google" 

我试图元= driver.find_element()工作得很好,所以我想也许有做所有的jQuery的定位更普遍的方式。这就是为什么我尝试execute_script。但是,似乎execute_script函数已损坏。我从sun.reflect,java.lang或org.openqa得到了很多错误...

P/S:如果有人知道如何在webdriver add_location_strategy,请告诉我关于它:D。它在硒中非常出色,我找不到在webdriver中实现它的方法。

+0

如果您向我们展示了您遇到的错误,它会更容易帮助。代码看起来很好,除了Google不在他们的头版上使用jQuery。 – jarib 2011-06-12 14:03:44

+0

这是我得到的: [远程服务器] sun.reflect.NativeConstructorAccessorImpl():-2:在'newInstance0' :$没有定义(警告:服务器没有提供任何堆栈跟踪信息 on)(Selenium: :WebDriver :: Error :: UnhandledError) 驱动程序信息:driver.version:EventFiringWebDriver(org.openqa.selenium.WebDriver 例外) .... 我只是使用jQuery定位器来选择元素。 – BaoNgoc 2011-06-12 14:11:56

回答

1

导航到所需的页面之后,但使用jQuery前:

# load the JavaScript file into memory as a string 
jQuerify = ... 

# add jQuery to the current page 
driver.execute_async_script(jQuerify) 

这里提到的JavaScript文件:

/*** dynamically load jQuery ***/ 
(function(callback) { 
    var JQUERY_URL = 'http://code.jquery.com/jquery-latest.min.js'; 
    if (typeof jQuery == 'undefined') { 
     var script=document.createElement('script'); 
     script.src = JQUERY_URL; 
     var head = document.getElementsByTagName('head')[0]; 
     var done = false; 
     script.onload = script.onreadystatechange = (function() { 
      if (!done && (!this.readyState 
        || this.readyState == 'loaded' 
        || this.readyState == 'complete')) { 
       done = true; 
       script.onload = script.onreadystatechange = null; 
       callback(); // tell WebDriver we are done 
       head.removeChild(script); 
      } 
     }); 
     head.appendChild(script); 
    } 
    else { 
     callback(); 
    } 
})(arguments[arguments.length - 1]); 

这个片段将被粘贴到人体的匿名函数WebDriver,将jQuery放在全局范围内。应该缓存文件内容以重复调用。

(从jQuerify大量举债)

哦,一般来说,你应该选择元素时坚持Ruby API。直接使用JavaScript被认为是一种解决方法,与WebDriver的精神背道而驰。