使用ruby mechanize保存文件

时间:2012-04-24 11:10:58

标签: ruby mechanize

我遇到代码问题(此代码可能会获取请求并下载生成的文件):

require 'rubygems'
require 'mechanize'
require 'hpricot'

OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE

user = "xxx"
pass = "xxx"
auth_key = "xxx"
ip = "xxx"

agent = Mechanize.new
page = agent.get("https://#{ip}/cgi-bin/welcome.cgi")
form = page.forms.first
form.username = user
form.password = Digest::MD5.hexdigest(pass + auth_key)
page = agent.submit form

page = agent.get("https://#{ip}/cgi-bin/config.exp")
form = page.forms.first
agent.pluggable_parser.default = Mechanize::FileSaver
agent.post("https://#{ip}/cgi-bin/config.exp", {"submitstatus" => "1"})

有了这个我有一个错误:

/var/lib/gems/1.8/gems/mechanize-2.4/lib/mechanize/http/agent.rb:291:in `fetch': 400 => Net::HTTPBadRequest for https://31.223.225.133/cgi-bin/config.exp -- unhandled response (Mechanize::ResponseCodeError)
 from /var/lib/gems/1.8/gems/mechanize-2.4/lib/mechanize.rb:407:in `get'
 from /home/lord/Dropbox/work/ruby/ruby_backup/backup.ru:22

如何模拟此wget请求以下载文件:

 `wget --no-check-certificate --load-cookies cookie --post-data='submitstatus=1' \
 --header='Host: 10.1.25.254' \
 --header='User-Agent: Mozilla/5.0' \
 --header='Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' \
 --header='Accept-Language: ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3' \
 --header='Accept-Encoding: gzip, deflate' \
 --header='Connection: keep-alive' \
 --header='Referer: https://10.1.25.254/sys_setting.htm' \
 --header='Content-Type: application/x-www-form-urlencoded' \
 --header='Content-Length: 14' \
 https://$ip/cgi-bin/config.exp`

提前谢谢

2 个答案:

答案 0 :(得分:0)

如果您通过调试代理(例如fiddler或charles)代理机械化和wget请求,您可以将它们并排比较,从而更好地理解问题。

答案 1 :(得分:0)

您是否尝试过Mechanize::Download

这是一个参考

Using WWW:Mechanize to download a file to disk without loading it all in memory first