0

I am trying to download a file on a page that is protected behind a login. The issue i am having is that once i obtain the download url, the file needs to be downloaded inside PhantomJS in order to have the active session. The make things more complicated the download is done by javascript. I click a url, it brings me to a temp page, javascript starts the download and then closes the page. Here is a rough diagram to explain what a human needs to do to download the file.

Login
  |
  V
Click Download
  |
  V
Browser redirect to /download?fileid=123
  |
  V
File automatically downloads when the page loads
  |
  V
Window closes automatically

I am at the point where i have "/download?fileid=123" stored in a string. I thought i would be able to use normal C# code to download this file, but it doesn't work as it doesn't detect the active session and redirects me to the login.

I need to be able to tell PhantomJS to navigate to this download url and it will be able to capture the file that is automatically downloaded by the javascript. I have performed the navigation, but i cant see anything while in debug that shows a file stream or anything that i can tap into.

Is is possible for me to capture this file download? I am using PhantomJS with selenium.

Dan Hastings
  • 3,241
  • 7
  • 34
  • 71

1 Answers1

1

I thought i would be able to use normal C# code to download this file, but it doesn't work as it doesn't detect the active session and redirects me to the login.

This sounds like a cookie issue!


Here's a IWebDriver extension method, which inserts all IWebDriver cookies into a HttpWebRequest, and downloads the file at the given url.

public static bool TryDownloadFile(this IWebDriver driver, string url, string fileName)
{
    try
    {
        // create HttpWebRequest
        Uri uri = new Uri(url);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);

        // insert cookies
        request.CookieContainer = new CookieContainer();
        foreach (OpenQA.Selenium.Cookie c in driver.Manage().Cookies.AllCookies)
        {
            System.Net.Cookie cookie =
                new System.Net.Cookie(c.Name, c.Value, c.Path, c.Domain);
            request.CookieContainer.Add(cookie);
        }

        // download file
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream responseStream = response.GetResponseStream())
        using (FileStream fileStream = File.Create(fileName))
        {
            var buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                fileStream.Write(buffer, 0, bytesRead);
            }
        }

        return true;
    }
    catch (Exception)
    {
        return false;
    }
}
budi
  • 6,351
  • 10
  • 55
  • 80