How to download a file using Capybara and Poltergeist - Ruby
20 Jun 18
In this tutorial, I explain how I managed to use Capybara and Poltergeist to download any file given that you are able to identify the url of the file you wish to download.
I quickly stumbled into an obstacle as phantomjs does not support file downloads and since Poltergeist is a wrapper around PhantomJS I was out of luck in having this kind of functionality out of the box. Also, adding support for this functionality in PhantomJS as i came to discover was not likely to happen.
I achieved this in the following steps. Credits
1. STEP 1
2. STEP 2
3. STEP 3
The final step was put everything together in a ruby method. I called it download. It expects a valid url as an argument. This is the url of the file you wish to download. How you get this url is upto you to figure out as per the requirements of your case.
The difference between the two is that
evaluate_script will always return a result. The return value will be converted back to Ruby objects. This is exactly what I needed as compared to
execute_script which always returns nil and is useful in cases where you don't care about the return value.
That's it! You should be able to integrate this in your ruby project to download any file using Capybara and Poltergeist. Please note however you may need to modify a few things in the download ruby method to work for your case.
In my case, the download url was dynamically provided through an Ajax call on the website page I was crawling. I needed a way to get this url. Luckily, Poltergeist has a method to inspect network traffic just as you would do on a normal browser. I used the loop method to wait for the url to be available as shown below
That's it guys! Hope this tutorial was helpful to anyone looking to achieve downloads using Capybara Poltergeist driver. Have any questions? Kindly feel free to ask me in the comments section below. Happy Coding!