如何基于水豚中的元素发送JavaScript [英] How to send JavaScript based in a element in capybara
问题描述
我正在寻找在水豚市做这样的事情:
I am looking to do something like this in Capybara:
browser.execute_script("arguments[0].setAttribute('value', 'value')", element)
以上行在selenium/ruby上运行,但是将execute_script与capybara一起使用仅需要1个参数(脚本),因此我无法定义希望在...上执行脚本的元素? >
The above line is run on selenium/ruby, but using execute_script with capybara takes only 1 parameter (the script), hence I am unable to define the element I wish to execute the script on... any ideas?
推荐答案
选项1-直接调用Selenium的execute_script
最快的解决方案是绕过Capybara API并直接调用Selenium-WebDriver的execute_script
方法.
The quickest solution would be to bypass the Capybara API and call Selenium-WebDriver's execute_script
method directly.
为此,您将需要使用以下命令访问底层的Selenium :: WebDriver :: Driver.
To do this, you will need to access the underlying Selenium::WebDriver::Driver using:
page.driver.browser
同样,传递给Selenium execute_script
的元素也必须是Selenium :: WebDriver :: Element(而不是Capybara :: Node :: Element).这是通过以下方式完成的:
As well, the elements that get passed to Selenium's execute_script
will need to be Selenium::WebDriver::Element (rather than the Capybara::Node::Element). This is done by:
element.native
例如,假设您有一个带有文本字段的页面:
As an example, say you have a page with the text field:
<input value="5" id="field">
然后,以下内容将更改该字段的值:
Then the following will change the field's value:
element = find('#field')
p element.value
#=> "5"
page.driver.browser.execute_script("arguments[0].setAttribute('value', 'value')", element.native)
p element.value
#=> "value"
选项2-修补水豚以允许自变量
如果需要经常执行此操作,则可以猴子修补Capybara的execute_script
方法以获取参数,将参数转换为Selenium对象,然后将其传递给Selenium-WebDriver的方法.补丁为:
If you need to do this frequently, you could monkey-patch Capybara's execute_script
method to take arguments, convert the arguments to Selenium objects and then pass it to Selenium-WebDriver's method. The patch would be:
require 'capybara'
class Capybara::Session
def execute_script(script, *args)
@touched = true
driver.execute_script(script, *args)
end
end
class Capybara::Selenium::Driver
def execute_script(script, *args)
args.map! { |e| e.kind_of?(Capybara::Node::Element) ? e.native : e }
browser.execute_script(script, *args)
end
end
这将允许您将Capybara元素传递给会话execute_script
方法:
This would then allow you to pass Capybara elements to the session execute_script
method:
element = page.find('#field')
p element.value
#=> "5"
page.execute_script("arguments[0].setAttribute('value', 'value')", element)
p element.value
#=> "value"
这篇关于如何基于水豚中的元素发送JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!