ruby-on-rails - 保持 Mechanize 页面超过请求边界

标签 ruby-on-rails ruby mechanize

我正在编写一个 ruby​​ 应用程序,它可以代表用户向远程博客发表评论。我的问题是我必须在 Controller 的 post 方法中使用相同的页面,以保持 session 处于事件状态并填写验证码:

应用程序/ Controller /comment_controller.rb

require 'mechanize'
class CommentController < ApplicationController
   def new
       agent = Mechanize.new
       @page = agent.get('http://blog.example.com')
       @captcha_src = @page.search("//div[@id='recaptcha_image']").search("//img")[1].attribute("src")
       #etc.
   end

   def post_comment
      # insert captcha, username, password + text into the form
      agent.submit(@page.form[0], @page.form[0].buttons.submitbutton) # Problem: page instance variable doesn't exist anymore
   end
end

我已经尝试将 page-instance-variable 保存在 Rails.cache 中,但是无法将 Mechanize 页面编码为字符串。

最佳答案

我写了一个有效的解决方案。它将隐藏变量和 cookie 保存在 base64 编码的字符串中,该字符串在隐藏字段中的请求之间传输。下面是要构建的代码:

require 'mechanize'
require 'stringio'
require 'base64'

class MechanizeWrapper
  attr_reader :page, :agent

  def initialize(url, useproxy = true)
    @agent = Mechanize.new
    @page = @agent.get(url)
  end

  def get_state()
    hidden_fields = {}
    cookie_jar = StringIO.new

    @page.search("//input[@type='hidden']").each do |hidden| 
      hidden_fields[hidden.path]=hidden.attribute('value').to_s
    end

    @agent.cookie_jar.dump_cookiestxt(cookie_jar);

    state = {:hidden_fields => hidden_fields.inspect, :cookie_jar => cookie_jar.string}
    Base64.encode64(state.inspect)
  end

  def put_state(state_enc)
    state = eval(Base64.decode64(state_enc))
    eval(state[:hidden_fields]).each do |path,value|  
      @page.search(path).first['value'] = value
    end    

    cookie_jar = StringIO.new(state[:cookie_jar])
    @agent.cookie_jar.load_cookiestxt(cookie_jar)
  end
end

关于ruby-on-rails - 保持 Mechanize 页面超过请求边界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9063036/

相关文章:

python - 使用 Python 填写 Ajax 表单

ruby-on-rails - 在 Linux 上运行的 Rails 和 https (ssl)

jquery - 将 onChange 事件附加到 Rails 中的选择列表

css - 如何避免 Rails 3.2 中的 CSS 延迟

html - 清理 HTML 并关闭不完整的标签

ruby - 可以像在 C# 中使用#region 一样在 Ruby 中使用 begin/end 吗?

JavaScript Rails 代码无法在 application.js 中运行

ruby-on-rails - activeadmin:为嵌套资源添加删除

perl - 我可以在 WWW::Mechanize 的 POST 中将空格编码为 %20 吗?

python - Mechanize 选择表格并输入文本