Jeremias Santos
Jeremias Santos

Reputation: 23

Download file with PhantomJS

I'm trying to download a file using PhantomJS, but when I click to download, no file is downloaded, I read that Phantomjs doesn't support downloads, but I need that, can you help me?

Here's the code from just the part when I try to download:

try
{
  checkbox = wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath("//form[@id='formDownload']//table[@class='fileTables']//tbody//tr//td//input[@class='checkbox']")));      
  checkbox[countLine - 1].Click();      
  wait.Until(ExpectedConditions.ElementExists(By.Id("all"))).Click();
}
catch (Exception ex)
{
   throw new Exception(ex.Message);
}

Upvotes: 2

Views: 2549

Answers (1)

Leon Barkan
Leon Barkan

Reputation: 2703

Ok what you need to do is:

  1. When you clicking on the file in your html you need to find the link of the file.

  2. you need to take the link and make httpRequest for getting the file.

Here is full function of the request (i making in easy for you, just find the link)

public static bool DownloadFile(string url, IWebDriver driver)
        {
            try
            {
                // Construct HTTP request to get the file
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
                httpRequest.CookieContainer = new System.Net.CookieContainer();

                for (int i = 0; i < driver.Manage().Cookies.AllCookies.Count - 1; i++)
                {
                    System.Net.Cookie ck = new System.Net.Cookie(driver.Manage().Cookies.AllCookies[i].Name, driver.Manage().Cookies.AllCookies[i].Value, driver.Manage().Cookies.AllCookies[i].Path, driver.Manage().Cookies.AllCookies[i].Domain);
                    httpRequest.CookieContainer.Add(ck);
                }

                httpRequest.Accept = "text/html, application/xhtml+xml, */*";
                httpRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";

                //HttpStatusCode responseStatus;

                // Get back the HTTP response for web server
                HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse();
                Stream httpResponseStream = httpResponse.GetResponseStream();

                // Define buffer and buffer size
                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int bytesRead = 0;

                // Read from response and write to file
                FileStream fileStream = File.Create(FilePath + "\\" + FileName + ".xls");
                while ((bytesRead = httpResponseStream.Read(buffer, 0, bufferSize)) != 0)
                {
                    fileStream.Write(buffer, 0, bytesRead);
                }

                return true;
            }
            catch (Exception ex)
            {
               return false;
            }
        }

Upvotes: 5

Related Questions