Selecting an option from dropdown form fields with Mechanize

Mechanize works great for uploading data through forms: it has great support for manipulating text fields, check boxes, and so on. Selecting the appropriate option from a dropdown is slightly more roundabout.

Mechanize supports only selecting options by their value, so if you know only the text label you want to select, you’ll need to iterate through the options first with a function link this:


def select_option(form, field_id, text)
value = nil
form.field_with(:id => field_id).options.each{|o| value = o if o.text == text }

raise ArgumentError, "No option with text '#{text}' in field '#{field_id}'" unless value
form.field_with(:id => field_id).value = value
end

With this function in your code, you can now get Mechanize to select dropdown values with

new_hotel_page.form_with(:method => ‘POST’) do |f|
select_option(f, ‘hotel_location_id’, location_name)
end.submit

As I said, this requires slightly more code than simply entering data in a text field, but it works fine.

This entry was posted in Automation, Mechanize, Ruby. Bookmark the permalink.