From da90024a96be2fc9d2e366c75d45c0fe602f56fe Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Tue, 18 May 2021 18:46:43 +0900 Subject: [PATCH] post form --- main.cr | 3 ++- src/mechanize.cr | 22 +++++++++++++++++++++- src/mechanize/form/field.cr | 8 ++------ 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/main.cr b/main.cr index 6ae6618..6bc360e 100644 --- a/main.cr +++ b/main.cr @@ -4,7 +4,8 @@ agent = Mechanize.new agent.request_headers = HTTP::Headers{"Foo" => "Bar"} params = {"hoge" => "hoge"} #page = agent.get("http://example.com/", params: params) -page = agent.post("http//example.com/") +query = {"foo" => "foo_value", "bar" => "bar_value"} +page = agent.post("http//example.com/", query: query) #puts page.code #puts page.body #puts page.css("h1").first.inner_text diff --git a/src/mechanize.cr b/src/mechanize.cr index 46aec5b..b84f256 100644 --- a/src/mechanize.cr +++ b/src/mechanize.cr @@ -23,7 +23,27 @@ class Mechanize node["enctype"] = "application/x-www-form-urlencoded" form = MechanizeCr::Form.new(node) - form.fields << MechanizeCr::FormContent::Field.new({"name" => "foo"}, "bar") + query.each do |k,v| + form.fields << MechanizeCr::FormContent::Field.new({"name" => k}, v) + end + #post_form(uri, form, headers) + end + + def post_form(uri, form, headers) + #cur_page = form.page || current_page || + # Page.new + + request_data = form.request_data + + headers = { + "Content-Type" => form.enctype, + "Content-Length" => request_data.size.to_s, + }.merge headers + + # fetch the page + page = @agent.fetch uri, :post, headers, [request_data], cur_page + add_to_history(page) + page end def request_headers diff --git a/src/mechanize/form/field.cr b/src/mechanize/form/field.cr index 74141aa..8e69f17 100644 --- a/src/mechanize/form/field.cr +++ b/src/mechanize/form/field.cr @@ -1,14 +1,10 @@ class MechanizeCr::FormContent::Field + property :node, :value def initialize(node : Hash(String, String), value : String = node["value"]) @node = node #@name = Mechanize::Util.html_unescape(node['name']) #@raw_value = value - #@value = if value.is_a? String - # Mechanize::Util.html_unescape(value) - # else - # value - # end -# + @value = value #@type = node['type'] end end