New*_*bie 3 ruby mechanize nokogiri
我尝试使用mechanize(Ruby)访问表单.在我的表格上,我有一个Radiobuttons的gorup.所以我想检查其中一个.
我写:
target_form = (page/:form).find{ |elem| elem['id'] == 'formid'}
target_form.radiobutton_with(:name => "radiobuttonname")[2].check
Run Code Online (Sandbox Code Playgroud)
在这一行中,我想检查值为2的单选按钮.但在这一行中,我收到一个错误:
: undefined method `radiobutton_with' for #<Nokogiri::XML::Element:0x9b86ea> (NoMethodError)
Run Code Online (Sandbox Code Playgroud)
出现问题是因为使用Mechanize页面作为Nokogiri文档(通过调用/方法,或search,或xpath等)返回Nokogiri元素,而不是使用特殊方法返回Mechanize元素.
如评论中所述,您可以确保Mechanize::Form通过使用该form_with方法来查找您的表单.
但是,有时您可以使用Nokogiri找到所需的元素,但不能使用Mechanize.例如,考虑一个页面,其中的<select>元素不在a中<form>.由于没有表单,因此无法使用Mechanize field_with方法查找select并获取Mechanize::Form::SelectList实例.
如果你有一个Nokogiri元素并且你想要Mechanize等价物,你可以通过将Nokogiri元素传递给构造函数来创建它.例如:
sel = Mechanize::Form::SelectList.new( page.at_xpath('//select[@name="city"]') )
Run Code Online (Sandbox Code Playgroud)
在你的情况下你有一个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 )
Run Code Online (Sandbox Code Playgroud)
PS上面的第一行更简单地实现了 target_form = page.at_css('#formid').
| 归档时间: |
|
| 查看次数: |
970 次 |
| 最近记录: |