Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save file downloaded by button click with Mechanize

Tags:

ruby

mechanize

I'm trying to use Mechanize to simulate clicking a button on a web page, which then would initiate a file download in a browser. This is a snippet of my code

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)

the output from pp button is displayed thus, which means it's the right button:

#<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">

but having issued the "agent.submit(form, button)" how can I get Mechanize to retrieve the file that would be sent to the browser on clicking that button?

I've had a search and found methods for getting web pages, or links , but didn't see anything to suit this case?

BTW I'm a complete newbie to both ruby and Mechanize, so sorry if this is a stupid question, but thanks for any responses!

M:

like image 704
user2373168 Avatar asked May 11 '13 15:05

user2373168


1 Answers

The file or page should be the returned by the submit:

response = agent.submit(form, button)
File.open('saved_file', 'wb'){|f| f << response.body}
like image 92
pguardiario Avatar answered Oct 06 '22 01:10

pguardiario