gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 16:30:54 26 4
gpt4 key购买 nike

我正在创建一个网站抓取工具。有一个表格用来改变当前页面。

这是我为 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 的任何内容。

最佳答案

调试 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

关于Ruby Net::HTTP::Post 提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42145320/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com