如何使用Mechanize按钮单击保存下载的文件

时间:2013-05-11 15:58:46

标签: ruby mechanize

我正在尝试使用Mechanize来模拟单击网页上的按钮,然后在浏览器中启动文件下载。这是我的代码片段

form = page.forms.first # => Mechanize::Form
form = agent.page.form_with(:name => "aspnetForm")

button = form.button_with(:value => "GPX file")
pp button

agent.submit(form, button)

因此显示pp按钮的输出,这意味着它是右键:

#<Mechanize::Form::Submit:0x89fe874
 @name="ctl00$ContentBody$btnGPXDL",
 @node=
  #(Element:0x44ff480 {
    name = "input",
    attributes = [
      #(Attr:0x44476d2 { name = "type", value = "submit" }),
      #(Attr:0x44476c8 {
        name = "name",
        value = "ctl00$ContentBody$btnGPXDL"
        }),
      #(Attr:0x44476be { name = "value", value = "GPX file" }),
      #(Attr:0x44476a0 { name = "id", value = "ctl00_ContentBody_btnGPXDL" })]
    }),
 @value="GPX file">

但已发出“agent.submit(表单,按钮)”如何让Mechanize检索将在点击该按钮时发送到浏览器的文件?

我有搜索并找到获取网页或链接的方法,但没有看到任何适合这种情况的内容?

BTW我是ruby和Mechanize的完全新手,很抱歉,如果这是一个愚蠢的问题,但感谢您的回复!

L:

1 个答案:

答案 0 :(得分:6)

文件或页面应该是submit:

返回的
response = agent.submit(form, button)
File.open('saved_file', 'wb'){|f| f << response.body}