Nokogiri错误:未定义的方法`radiobutton_with’ – 为什么?
我尝试使用mechanize(Ruby)访问表单。 在我的表格上,我有一个Radiobuttons的gorup。 所以我想检查其中一个。
我写:
target_form = (page/:form).find{ |elem| elem['id'] == 'formid'} target_form.radiobutton_with(:name => "radiobuttonname")[2].check
在这一行中,我想检查值为2的单选按钮。但在这一行中,我收到一个错误:
: undefined method `radiobutton_with' for # (NoMethodError)
出现问题是因为使用Mechanize页面作为Nokogiri文档(通过调用/
method,或search
或xpath
等)返回Nokogiri元素,而不是使用特殊方法返回Mechanize元素。
如评论中所述,您可以确保通过使用form_with
方法获取Mechanize::Form
来查找您的表单。
但是,有时您可以使用Nokogiri找到所需的元素,但不能使用Mechanize。 例如,考虑一个页面,其中元素不在
。 由于没有表单,因此您无法使用Mechanize field_with
方法查找select并获取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 )
PS上面的第一行更简单地通过 target_form = page.at_css('#formid')
。