2010-03-18 48 views
3

我尝试使用机械化(Ruby)访问表单。 在我的表格上,我有一个Radiobuttons的gorup。 所以我想检查其中的一个。Nokogiri错误:未定义的方法`radiobutton_with' - 为什么?

我写道:

target_form = (page/:form).find{ |elem| elem['id'] == 'formid'} 
target_form.radiobutton_with(:name => "radiobuttonname")[2].check 

在此行中我想用2 但在这条线的值来检查单选按钮,我得到一个错误:

: undefined method `radiobutton_with' for #<Nokogiri::XML::Element:0x9b86ea> (NoMethodError) 
+1

根据文档,你的表单应该是'Mechanize :: Form'类,而不是'Nokogiri :: XML :: Element'。你是如何得到'target_form'的? – 2010-03-18 11:06:20

+0

target_form: target_form =(page /:form).find {| elem | elem ['id'] =='formid'} – Newbie 2010-03-18 11:20:46

+0

您应该使用'Mechanize :: Page#form_with'方法来获取表单。顺便说一句,我不确定你的页面是不是“Mechanize :: Page”。 – 2010-03-18 11:51:20

回答

5

问题发生因为使用机械化页面作为Nokogiri文档(通过调用/方法或searchxpath等)将返回Nokogiri元素,而不是Mechanize元素及其特殊方法。

正如在评论中指出的那样,您可以通过使用form_with方法来确保获得Mechanize::Form来代替您的表单。

但是,有时您可以使用Nokogiri找到您想要的元素,但不能使用Mechanize。例如,考虑一个<select>元素不在<form>内的页面。由于没有表单,因此无法使用Mechanize field_with方法查找选择并获取Mechanize::Form::SelectList实例。

如果你有一个Nokogiri元素并且你想要Mechanize等价物,你可以通过将Nokogiri元素传递给构造函数来创建它。例如:

sel = Mechanize::Form::SelectList.new(page.at_xpath('//select[@name="city"]')) 

在你的情况下,你有一个Nokogiri::XML::Element,想一个Mechanize::Form

# Find the xml element 
target_form = (page/:form).find{ |elem| elem['id'] == 'formid'} 
target_form = Mechanize::Form.new(target_form) 

附:上面的第一行更简单地通过target_form = page.at_css('#formid')实现。

+0

要真正能够提交表单,您必须将最后一行更改为'target_form = Mechanize :: Form.new(target_form,mech_object,page)' – raphinesse 2012-02-05 13:52:01

+0

@raphinesse哦?你的话我记住了。什么是“mech_object”对象? – Phrogz 2012-02-05 14:18:39

+0

您的'代理','机械化'对象。有关更多详细信息,请参阅[机械化::表单#新文档](http://mechanize.rubyforge.org/Mechanize/Form.html#method-c-new)。如果你看看[Mechanize :: Form#submit的源代码](http://mechanize.rubyforge.org/Mechanize/Form.html#method-i-submit),你会注意到它试图调用'@mech .submit'在没有提供'mech'参数时会失败。我猜想'page'参数也是如此。 – raphinesse 2012-02-05 14:35:49

相关问题