0

I'm picking up ruby mechanize & getting tripped up from the start...

Why does this code:

    #!/usr/bin/ruby env
    require 'rubygems'
    require 'mechanize'

    agent = Mechanize.new
    page = agent.get('http://linkedin.com/')

    #pp page

    form = page.form.first
    #form.fields.each { |f| puts f.name }
    #pp page

spit out...

/home/ubuntu/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/mechanize-2.7.4/lib/mechanize/form.rb:217:in `method_missing': undefined method `first' for #<Mechanize::Form:0x007f9f2cf1ced0> (NoMethodError)
from 1-li.rb:10:in `<main>'
orde
  • 5,233
  • 6
  • 31
  • 33

2 Answers2

1

You want to use the forms method instead of the form method.

Per the documentation, the forms method returns "a list of all form tags", and you can then method-chain a first method. For example:

require 'mechanize'
mechanize = Mechanize.new
page = mechanize.get('http://www.w3schools.com/html/html_forms.asp')
forms = page.forms
forms.class              #=> Array
form = forms.first
form.class               #=> Mechanize::Form 
orde
  • 5,233
  • 6
  • 31
  • 33
0

To get the first form on the page, use use page.form or page.forms.first

pguardiario
  • 53,827
  • 19
  • 119
  • 159