使页面机械化超出请求边界 [英] keep mechanize page over request boundaries

查看:67
本文介绍了使页面机械化超出请求边界的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个ruby应用程序,该应用程序可以代表用户向远程博客发布评论.我的问题是,我必须在控制器的post方法中使用相同的页面,才能保持会话的活动状态&填写验证码:

Im writing a ruby application that can post comments on behalf of the user to a remote blog. My problem is that i have to use the same page in the post method of the controller, to keep the session alive & to fill out a captcha:

app/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中,但是机械化的页面无法编组为字符串.

I've already tried to save the page-instance-variable in Rails.cache but mechanized pages can't be marshalled to string.

推荐答案

我写了一个可行的解决方案.它将隐藏变量和cookie保存在base64编码的字符串中,该字符串在隐藏字段中的请求之间进行传递.以下是要构建的代码:

I wrote a working solution. It saves the hidden-variables and the cookies in a base64 encoded string which iam transferring between requests in a hidden field. Heres the code to build upon:

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

这篇关于使页面机械化超出请求边界的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆