Gem RestClient 使用过程中的网页 POST 请求问题

donychen · June 09, 2015 · Last by wangyudongdom replied at November 29, 2017 · 6361 hits

Hello 大家好,没错,作为一枚新手 ruby 菜鸟以及 HTML 小白,我又来了。。。

今天想问大家一个问题: 如何使用 ruby gem 中的 restclient 来登陆一个网页,并返回登陆后的界面。 或者大家有其他好方法,可以达到这个目的。 前提是:用命令行执行脚本,不能用模拟打开浏览器的方法,类似 waitri-webdriver。服务器端没有浏览器可以用(或者我小白,还不知道?) 麻烦各位大神了。 下面是我用 restclient 的过程中遇到的问题。

====================================分割线=========================================

模拟登陆 Ruby China 社区 上图是用 firebug 查看到的 post 请求的参数,根据参数写出 post 登陆代码。

代码如下:

require 'rubygems'
require 'restclient'

LOGIN_URL = "https://ruby-china.org/account/sign_in"

page = RestClient.post(LOGIN_URL, {'user[login]'=>'xxxx', 'user[password]'=>'xxxx', 'user[remember_me]'=>'0', 'commit'=>'登录', 'utf8'=>'✓', 'authenticlty_token'=>'xxxxxxxxxxxxxxxxxxxxxxxx'})

这里会报一个如下的错误: gems/ruby-2.2-head/gems/rest-client-1.8.0/lib/restclient/abstract_response.rb:65:in `return!': 302 Found (RestClient::Found) 网页我写的参数通过了,但是网页没有跳转到我想要的结果去。

我在网上查了一下,看到一段 java 代码说要根据重定向返回的 response 来 get 新的页面。我又写了如下代码:

require 'rubygems'
require 'restclient'

LOGIN_URL = "https://ruby-china.org/account/sign_in"

page = RestClient.post(LOGIN_URL, {'user[login]'=>'xxxx', 'user[password]'=>'xxxx', 'user[remember_me]'=>'0', 'commit'=>'登录', 'utf8'=>'✓', 'authenticlty_token'=>'xxxxxxxxxxxxxxxxxxxxxxxx'}) {|response, request, result, &block|
  if [301, 302, 307].include? response.code
    #response.follow_redirection(request, result, &block)
    puts response.cookies
  else
    response.return!(request, result, &block)
  end
}

但是会提示我 instance variable @cookie_jar not initialized 应该是没拿到 cookie。

可以显示到 response.headers,这里面有个链接 用 response.headers[:location] 可以拿到,但是用 get 方法打开这个链接后,我发现还是登陆前的页面。

====================================分割线=========================================

求助!求助!感激不尽!

咦,怎么上传不了图片呢?

现在我发现用一个名叫 mechanize 的 ruby gem,可以达到目的,但是我还是不明白为什么 restclient 不能够完成任务。不知道到有没有大神解答。

Format your code first. RestClient can do this. curb version, curb like rest-client

#4 楼 @flowerwrong 非常感谢,以前还不懂怎么把代码弄成 ruby 的格式,现在终于知道啦。 你的答案里面有好多值得参考的地方,再次感谢。

重新上传图片,之前你可能遇到上传服务器抽风了

#6 楼 @huacnlee 谢啦,我试了一下,果然可以了

初学者友情帮顶~

花费很多时间去规避 REST Client bug,不如省下时间去使用 WisdomTool REST Client,它支持自动化测试 RESTful API,输出精美的测试报告,并且自动生成 RESTful API 文档。 工具很精悍! https://github.com/wisdomtool/rest-client

Most of REST Client tools do not support automated testing.

Once used a tool called WisdomTool REST Client supports automated testing, output exquisite report, and automatically generating RESTful API document.

Very powerful !

https://github.com/wisdomtool/rest-client

You need to Sign in before reply, if you don't have an account, please Sign up first.