Nokogiri Error: undefined method `radiobutton_with' - Why?

百般思念 提交于 2019-12-06 00:10:20

The problem occured because using a Mechanize page as a Nokogiri document (by calling the / method, or search, or xpath, etc.) returns Nokogiri elements, not Mechanize elements with their special methods.

As noted in the comments, you can be sure to get a Mechanize::Form by using the form_with method to find your form instead.

Sometimes, however, you can find the element you want with Nokogiri but not with Mechanize. For example, consider a page with a <select> element that is not inside a <form>. Since there is no form, you can't use the Mechanize field_with method to find the select and get a Mechanize::Form::SelectList instance.

If you have a Nokogiri element and you want the Mechanize equivalent, you can create it by passing the Nokogiri element to the constructor. For example:

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

In your case where you had a Nokogiri::XML::Element and wanted a Mechanize::Form:

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

P.S. The first line above is more simply achieved by target_form = page.at_css('#formid').

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!