1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Finding Forms


The next most common thing you'll want to find in a page are forms. Forms are found in exactly the same way links are, with Page#forms, Page#form_with and Page#forms_with. All of these methods are defined by the same DSL, so they all work in exactly the same way. The only thing that differs here is that Mechanize::Form objects respond to different messages.

  • method - Must be either GET or POST.
  • action - The URL to submit the form to.
  • name - The value of the form tag's name attribute. This is also accessible using the shorthand String-only argument discussed below.
  • dom_id - As with links, the value of the id attribute.

Since it's most common for forms to have a name attribute, you'll most likely be searching for forms in that way. To make this a little easier, you can omit the hash argument altogether and pass a single String argument. Mechanize will then turn that into a hash argument with a :name key. For example, page.form('q') will be turned into the equivalent of page.form(:name => 'q'). You'll see this shorthand used often in Mechanize code. And this isn't something special for forms, this works with any of the search-type methods, but usually only forms set the name attribute.

The following example loads up Google and finds the search form in two ways. Note that its name attribute is 'f' and it submits to the /search url.

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

form1 = page.form_with('f')
form2 = page.form_with(:action => '/search')

if form1 === form2
  puts "They are the same form"
  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. The Mechanize 2.0 Handbook
  6. Finding Forms

©2014 About.com. All rights reserved.