无效的代码:login_form = page.form_with(:method => 'post')
和有效的代码:login_form = page.form_with(:method => 'POST')
我通过 puts page.forms.inspect
检查了表单对象并得到
[#<WWW::Mechanize::Form
{name nil}
{method "POST"}
....]
html源码:
<form class="login" method="post"> <fieldset>
<legend>Members Login</legend>
<div>
<label for="auth_username">Username</label> <input id="auth_username" name="auth_username">
</div>
<div>
<label for="auth_password">Password</label> <input id="auth_password" name="auth_password" type="password">
</div>
</fieldset>
<div class="buttons">
<input name="auth_login" type="submit" value="Login"><p class="note"><a href="/forgotpassword">Forgot your password?</a></p>
</div>
</form>
这是一个错误还是预期的行为?
最佳答案
查看源代码,可能是 Mechanize 应该像那样工作。它在获取表单时强制表单方法为大写;当您想要匹配它时,您应该以大写形式提供该方法。您可以 ping Mechanize 人员并询问他们是否应该像那样工作。
在 Mechanize.submit 中,它在比较之前强制表单方法为大写:
def submit(form, button=nil, headers={})
...
case form.method.upcase
when 'POST'
...
when 'GET'
...
end
...
end
再次在 Form.initialize 中,该方法被强制为大写:
def initialize(node, mech=nil, page=nil)
...
@method = (node['method'] || 'GET').upcase
但是在 page.rb 中是 Mechanize 将表单(或链接、基础、框架或 iframe)与您提供的参数进行匹配的代码,您传入的参数不会强制为大写,因此它是区分大小写的匹配:
def #{type}s_with(criteria)
criteria = {:name => criteria} if String === criteria
f = #{type}s.find_all do |thing|
criteria.all? { |k,v| v === thing.send(k) }
end
yield f if block_given?
f
end
好吧,如果你传入一个字符串,它是一个区分大小写的匹配。但是如果你传入一个正则表达式,它就是一个正则表达式匹配。所以你应该能够做到这一点:
login_form = page.form_with(:method => /post/i)
并让它正常工作。但我可能只是传入一个大写的字符串,给 Mechanize 人员发送一封电子邮件,然后继续。
关于ruby - 无法使用字符串 'post' 但使用 'POST' 识别表单。 html 包含 'post',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2165834/