Ruby 机械化如何发送同名的多个参数
Ruby Mechanize how to send multiple params with same name
我正在尝试执行一个 post 请求,其中对同一个名称使用多个值,html 类似于:
<input name="opt[]" value="1"/>
<input name="opt[]" value="2"/>
<input name="opt[]" value="3"/>
通过机械化,我正在做类似的事情:
params = {'opt[]' => [1,2,3]}
agent.post 'url', params
运气不好。
我试过 opt: [1,2,3]
等其他选项,但也不成功。
您应该能够 post 它们作为字符串:
agent.post url, 'opt[]=1&opt[]=2&opt[]=3'
根据 Documentation for Mechanize and the discussion in this GitHub Issue 提交这些参数的正确方法是使用二维数组,如下所示
params = [["opt[]",1],["opt[]",2],["opt[]",3]]
agent.post 'url', params
在阅读 GitHub 问题时,这似乎是一个已知的功能限制,他们正在或正在计划努力解决这个问题,但目前这是正确的提交方法。如果您更愿意使用 Hash
结构操作就不会那么困难,例如
def process_to_mechanize_params(h)
h.map do |k,v|
if v.is_a?(Array)
v.map {|e| ["#{k}[]",e]}
else
[[k.to_s,v]]
end
end.flatten(1)
end
然后你可以使用
params = {'opt' => [1,2,3],'value' => 22, another_value: 'here'}
process_to_mechanize_params(params)
#=>=> [["opt[]", 1], ["opt[]", 2], ["opt[]", 3], ["value", 22], ["another_value", "here"]]
希望这对您有所帮助。正如@pguardiario 指出的那样,String 也是可以接受的,但我觉得它可能会降低可读性。
我正在尝试执行一个 post 请求,其中对同一个名称使用多个值,html 类似于:
<input name="opt[]" value="1"/>
<input name="opt[]" value="2"/>
<input name="opt[]" value="3"/>
通过机械化,我正在做类似的事情:
params = {'opt[]' => [1,2,3]}
agent.post 'url', params
运气不好。
我试过 opt: [1,2,3]
等其他选项,但也不成功。
您应该能够 post 它们作为字符串:
agent.post url, 'opt[]=1&opt[]=2&opt[]=3'
根据 Documentation for Mechanize and the discussion in this GitHub Issue 提交这些参数的正确方法是使用二维数组,如下所示
params = [["opt[]",1],["opt[]",2],["opt[]",3]]
agent.post 'url', params
在阅读 GitHub 问题时,这似乎是一个已知的功能限制,他们正在或正在计划努力解决这个问题,但目前这是正确的提交方法。如果您更愿意使用 Hash
结构操作就不会那么困难,例如
def process_to_mechanize_params(h)
h.map do |k,v|
if v.is_a?(Array)
v.map {|e| ["#{k}[]",e]}
else
[[k.to_s,v]]
end
end.flatten(1)
end
然后你可以使用
params = {'opt' => [1,2,3],'value' => 22, another_value: 'here'}
process_to_mechanize_params(params)
#=>=> [["opt[]", 1], ["opt[]", 2], ["opt[]", 3], ["value", 22], ["another_value", "here"]]
希望这对您有所帮助。正如@pguardiario 指出的那样,String 也是可以接受的,但我觉得它可能会降低可读性。