Skip to content

Instantly share code, notes, and snippets.

@xianhuazhou
Created January 15, 2010 03:54
Show Gist options
  • Save xianhuazhou/277798 to your computer and use it in GitHub Desktop.
Save xianhuazhou/277798 to your computer and use it in GitHub Desktop.
find all available fields/values from a from by Hpricot
# encoding: utf-8
require 'rubygems'
require 'hpricot'
def find_fields_from_form(form)
fields = {}
return fields unless form.is_a? Hpricot::Elem
set_parameter = Proc.new {|name, value|
case name
when /^(.+)\[\]$/
name = $1
fields[name] = [] if fields[name].nil?
fields[name] << value
when /^(.+)\[(.+?)\]/
name = $1
fields[name] = {} if fields[name].nil?
fields[name][$2] = value
else
fields[name] = value
end
}
form.search('select, input').each do |node|
next if node['name'].nil? or ['checkbox', 'radio'].include?(node['type'])
if node.name.eql? 'select'
no = node.search('option[@selected]').first || node.search("option").first
set_parameter.call(node['name'], no['value']) if no
else
set_parameter.call(node['name'], node['value'])
end
end
form.search('input[@checked]').each do |node|
set_parameter.call(node['name'], node['value'])
end
form.search('textarea').each do |node|
set_parameter.call(node['name'], node.inner_html)
end
fields
end
if __FILE__ == $0
require 'open-uri'
form = Hpricot(open('http://redmine.ruby-lang.org/login')).search('form').last
p find_fields_from_form(form)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment