如何从Mechanize :: File对象转换为Mechanize :: Page对象?

我有一个登录表单的页面。 登录后有一些重定向。 第一个看起来像这样:

#"no-cache=\"set-cookie\"", "content-length"=>"114", "set-cookie"=>"JSESSIONID=GdJnPVnhtN91KZfQPc3QzM1NLCyWDsnyvpGg8LL0Knnz3RgqxLFs!1803804592!-2134626567; path=/; secure, COOKIE_TEST=Aslyn; secure", "x-powered-by"=>"Servlet/2.4 JSP/2.0"}, @body="\r\n\r\n \r\n \r\n \r\n", @uri=#> 

所以当我在这里做一个page.class时,我得到了

 Mechanize::File 

如何将其转换为Mechanize::Page


@pguardiario

为了更好地解释我的原始消息中的代码存储在页面中。

当我做page.class时,我得到Mechanize :: File

那么我就执行上面的代码:

 agent = Mechanize.new agent.post_connect_hooks << lambda {|http| http[:response].content_type = 'text/html'} 

所以我这样做:agent.get(page.uri.to_s)或事件尝试使用任何url agent.get(“ https://www.manageyourloans.com/MYL ”)我收到一个错误:ArgumentError:错误的参数数量(4对1)

我甚至试过这个:

 agent = Mechanize.new { |a| a.post_connect_hooks << lambda { |_,_,response,_| if response.content_type.nil? || response.content_type.empty? response.content_type = 'text/html' end } } 

我的问题是,一旦我这样做,我如何将上一页转换为Mechanize :: Page?

您可以通过获取文件对象中包含的正文并将其作为新页面的正文传递,从Mechanize :: File转换为Mechanize :: Page:

 irb(main):001:0> require 'mechanize' true irb(main):002:0> file = Mechanize::File.new(URI.parse('http://foo.com'),nil,File.read('foo.html')) # > 

首先,我创建了一个伪造的Mechanize :: File对象,只是为了跟随示例代码。 您可以在:body查看它读取的文件的内容。

当Mechanize :: File对象无法确定真正的内容类型时,它会创建一个Mechanize :: File对象。

 irb(main):003:0> page = Mechanize::Page.new(URI.parse('http://foo.com'),nil,file.body) # "text/html" }, attr_accessor :uri = #, attr_reader :bases = nil, attr_reader :encodings = [ [0] nil, [1] "US-ASCII" ], attr_reader :forms = nil, attr_reader :frames = nil, attr_reader :iframes = nil, attr_reader :labels = nil, attr_reader :labels_hash = nil, attr_reader :links = nil, attr_reader :meta_refresh = nil, attr_reader :parser = nil, attr_reader :title = nil > irb(main):004:0> page.class Mechanize::Page < Mechanize::File 

只需传入文件对象的主体,让Mechanize转换为您应该知道的内容。

我喜欢@The Tin Man的回答,但强制回复的内容类型可能更简单:

 agent.post_connect_hooks << lambda {|http| http[:response].content_type = 'text/html'}