使用Mechanize捕获POST请求

时间:2011-06-03 03:06:21

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

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

来自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

2 个答案:

答案 0 :(得分: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")

答案 1 :(得分:-2)

post方法将参数作为哈希值。尝试:

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

相关问题