Ruby Net :: HTTP :: Post提交表单

时间:2017-02-09 19:33:20

标签: ruby forms post net-http

我正在努力创建一个网站抓取工具。有一个用于更改当前页面的表单。

这是我提交POST请求表单的方式,但它似乎一遍又一遍地获取同一页面。

以下是一些示例代码:

pages = {
 "total_pages" => 19,
 "p1" => '1234/1456/78990/123324345/12143343214345/231432143/12432412/435435/',
 "p2" => '1432424/123421421/345/435/6/65/5/34/3/2/21/1243',
..
..
..    
}


idx = 1
p_count = pages["total_pages"]

#set up the HTTP request to change pages to get all the auction results
uri = URI.parse("http://somerandomwebsite.com?listings")
http = Net::HTTP.new(uri.host, uri.port)
req = Net::HTTP::Post.new(uri.request_uri)

p_count.times do
  puts "On loop sequence: #{idx}"
  pg_num = "p#{idx}"
  pg_content = pages["#{pg_num}"]
  req.set_form_data({"page" => "#{pg_num}", "#{pg_num}" => "#{pg_content}"})

  response = http.request(req)
  page = Nokogiri::HTML(response.body)
  idx = idx + 1
end

看起来page永远不会改变。有没有办法看到每次我想确保正确的参数传递时,完整的请求是什么样的?似乎几乎无法确定req的任何内容。

1 个答案:

答案 0 :(得分:1)

调试HTTP的一个好方法是利用http://httpbin.org

require 'net/http'
uri = URI('http://httpbin.org/post')
res = Net::HTTP.post_form(uri, 'q' => 'ruby', 'max' => '50')
puts res.body

返回:

# >> {
# >>   "args": {}, 
# >>   "data": "", 
# >>   "files": {}, 
# >>   "form": {
# >>     "max": "50", 
# >>     "q": "ruby"
# >>   }, 
# >>   "headers": {
# >>     "Accept": "*/*", 
# >>     "Accept-Encoding": "gzip;q=1.0,deflate;q=0.6,identity;q=0.3", 
# >>     "Content-Length": "13", 
# >>     "Content-Type": "application/x-www-form-urlencoded", 
# >>     "Host": "httpbin.org", 
# >>     "User-Agent": "Ruby"
# >>   }, 
# >>   "json": null, 
# >>   "origin": "216.69.191.1", 
# >>   "url": "http://httpbin.org/post"
# >> }

那就是说,我建议不要使用Net :: HTTP。 Ruby有很多很棒的HTTP客户端,可以更容易地编写代码。例如,使用HTTPClient

是同样的事情
require 'httpclient'
clnt = HTTPClient.new
res = clnt.post('http://httpbin.org/post', 'q' => 'ruby', 'max' => '50')
puts res.body

# >> {
# >>   "args": {}, 
# >>   "data": "", 
# >>   "files": {}, 
# >>   "form": {
# >>     "max": "50", 
# >>     "q": "ruby"
# >>   }, 
# >>   "headers": {
# >>     "Accept": "*/*", 
# >>     "Content-Length": "13", 
# >>     "Content-Type": "application/x-www-form-urlencoded", 
# >>     "Date": "Thu, 09 Feb 2017 20:03:57 GMT", 
# >>     "Host": "httpbin.org", 
# >>     "User-Agent": "HTTPClient/1.0 (2.8.3, ruby 2.4.0 (2016-12-24))"
# >>   }, 
# >>   "json": null, 
# >>   "origin": "216.69.191.1", 
# >>   "url": "http://httpbin.org/post"
# >> }

这是未经测试的代码,因为您没有告诉我们足够的代码,但它是我开始做您正在做的事情的地方:

require 'httpclient'

BASE_URL = 'http://somerandomwebsite.com?listings'
PAGES = [
 '1234/1456/78990/123324345/12143343214345/231432143/12432412/435435/',
 '1432424/123421421/345/435/6/65/5/34/3/2/21/1243',
]

clnt = HTTPClient.new

PAGES.each.with_index(1) do |page, idx|
  puts "On loop sequence: #{idx}"

  response = clnt.post(BASE_URL, 'page' => idx, idx => page)

  doc = Nokogiri::HTML(response.body)
  # ...
end