【问题标题】:POST request capture with Mechanize使用 Mechanize 捕获 POST 请求
【发布时间】:2011-09-07 12:45:00
【问题描述】:

我正在尝试使用 Mechanize 来捕获无法通过表单实现的 POST 请求,因为该表单位于阻止直接通过 javascript 加载的 iframe 内。

以下是来自 Google Chrome 的示例请求中的 HTTP 标头(注意 paradalinea 参数)

Request URL:http://www.etr.gov.ar/getSmsResponse.php
Request Method:POST
Status Code:200 OK
Request Headers
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:es-419,es;q=0.8
Connection:keep-alive
Content-Length:21
Content-Type:application/x-www-form-urlencoded
Host:www.etr.gov.ar
Origin:http://www.etr.gov.ar
Referer:http://www.etr.gov.ar/cont-cuandollega.php
User-Agent:Mozilla/5.0 (X11; Linux i686) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.30 Safari/534.30
X-Requested-With:XMLHttpRequest

Form Dataview URL
parada:4152
linea:112

Response Headers
Connection:close
Content-Length:111
Content-Type:text/html
Date:Fri, 03 Jun 2011 02:35:45 GMT
Server:Microsoft-IIS/7.5
X-Powered-By:PHP/5.1.2
ASP.NETl

而这个例子的内容是:

Linea 112N: 0min. 379mts., siguiente 25min. 9937mts. - Linea 112R: 81min. 24349mts., siguiente 101min. 30548mts

我用 mechanize 尝试的是以下 ruby​​ 脚本,但我得到一个空白页作为响应:

require 'mechanize'
agent = WWW::Mechanize.new
agent.post("http://www.etr.gov.ar/getSmsResponse.php", "parada" => "4152", "linea"=>"112")

我会做错什么?非常感谢。

更新:将 POST 作为哈希传递非常有效。要渲染内容,我只需要agent.post.content

【问题讨论】:

    标签: ruby-on-rails ruby post screen-scraping mechanize


    【解决方案1】:

    post 方法期望参数为哈希值。试试:

    agent.post("http://www.etr.gov.ar/getSmsResponse.php", {"parada" => "4152", "linea"=>"112"})
    

    【讨论】:

    • 我投了反对票,因为 Ruby 解释此代码和原始代码之间的参数的方式没有区别。这并不能解决问题。
    • 很公平。感谢您指出这一点。我测试了它,你是对的。
    【解决方案2】:

    实际上,您的原始代码运行良好。您只需将其打印为agent.post.content 即可查看结果。


    回复mightilybix的回答:

    您的代码在不使用 { 和 } 传递哈希的情况下工作的原因是因为 Ruby 有一个特性,如果您将哈希作为函数的最后一个参数传递,那么您不需要包含大括号。例如:

    def test(str, params)
      puts str
      params.each { |param| puts param }
    end
    

    调用:

    test("hello", {"animal" => "cat", "gender" => "m"})
    

    和调用完全一样:

    test("hello", "animal" => "cat", "gender" => "m")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-16
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多