From cbcf025c3318df5be307269e9feddfc38ee662ea Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Thu, 27 May 2021 07:40:25 +0900 Subject: [PATCH] implementing page#forms and fields --- main.cr | 4 ++-- src/mechanize/form.cr | 24 +++++++++++++++++++++++- src/mechanize/node.cr | 1 + src/mechanize/page.cr | 12 +++--------- 4 files changed, 29 insertions(+), 12 deletions(-) diff --git a/main.cr b/main.cr index 5e3c7b2..f675518 100644 --- a/main.cr +++ b/main.cr @@ -3,8 +3,8 @@ require "./src/mechanize.cr" agent = Mechanize.new agent.request_headers = HTTP::Headers{"Foo" => "Bar"} params = {"hoge" => "hoge"} -page = agent.get("https://kowabana.jp/users/sign_in/", params: params) -page.forms +page = agent.get("http://example.com/", params: params) +form = page.forms[0] #query = {"foo" => "foo_value", "bar" => "bar_value"} #page = agent.post("http://example.com/", query: query) #puts page.code diff --git a/src/mechanize/form.cr b/src/mechanize/form.cr index 890377b..bd685a2 100644 --- a/src/mechanize/form.cr +++ b/src/mechanize/form.cr @@ -51,7 +51,9 @@ class MechanizeCr::Form def parse @fields = Array(MechanizeCr::FormContent::Field).new @checkboxes = Array(MechanizeCr::FormContent::CheckBox).new - @node.css("input").not_nil!.each do |node| + @node.css("input").not_nil!.each do |html_node| + html_node = html_node.as(Myhtml::Node) + @fields << MechanizeCr::FormContent::Field.new(html_node) end end @@ -61,4 +63,24 @@ class MechanizeCr::Form acc + URI::Params.encode(hash) + '&' end.rchop end + + def fields_with(criteria) + value = Hash(String,String).new + if String === criteria + value = {"name" => criteria} + else + # TODO + # when args whose type isn't String is given + end + fields.select do |field| + value.all? do |k,v| + v === field.name + end + end + end + + def field_with(criteria) + f = fields_with(criteria) + f.empty? ? Array(MechanizeCr::FormContent::Field).new : f.first + end end diff --git a/src/mechanize/node.cr b/src/mechanize/node.cr index 6b8e50d..2a5d5f7 100644 --- a/src/mechanize/node.cr +++ b/src/mechanize/node.cr @@ -13,4 +13,5 @@ struct Myhtml::Node delegate :[], to: attributes delegate :[]=, to: attributes delegate :[]?, to: attributes + delegate :fetch, to: attributes end diff --git a/src/mechanize/page.cr b/src/mechanize/page.cr index cb2fede..3b459c9 100644 --- a/src/mechanize/page.cr +++ b/src/mechanize/page.cr @@ -16,16 +16,10 @@ class MechanizeCr::Page < MechanizeCr::File end def forms - #@forms ||= css("form").map do |html_form| - # form = Mechanize::Form.new(html_form, @mech, self) - # form.attributes["action"]# ||= @uri.to_s - # form - #end - - forms = css("form").each do |html_form| + forms = css("form").map do |html_form| form = MechanizeCr::Form.new(html_form) - puts form.action# ||= @uri.to_s + form.action ||= @uri.to_s form - end + end.to_a end end