C# 使用PhantomJS下载文件
我试图使用C# 使用PhantomJS下载文件,c#,selenium,webdriver,phantomjs,C#,Selenium,Webdriver,Phantomjs,我试图使用PhantomJS下载一个文件,但是当我点击下载时,没有下载任何文件,我读到PhantomJS不支持下载,但我需要它,你能帮我吗 以下是我尝试下载时部分的代码: try { checkbox = wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath("//form[@id='formDownload']//table[@class='fileTables']//tbody//tr//td//inp
PhantomJS
下载一个文件,但是当我点击下载时,没有下载任何文件,我读到PhantomJS
不支持下载,但我需要它,你能帮我吗
以下是我尝试下载时部分的代码:
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);
}
好的,您需要做的是:
公共静态bool下载文件(字符串url,IWebDriver驱动程序)
{
尝试
{
//构造HTTP请求以获取文件
HttpWebRequest httpRequest=(HttpWebRequest)WebRequest.Create(url);
httpRequest.CookieContainer=new System.Net.CookieContainer();
对于(int i=0;i
如果下载依赖于会话(cookie)-怎么办?你可以看到我在我的函数中处理cookie,phantomJS拥有你需要的所有cookie。我会的,我在一个显示文件链接的网站上测试了这个功能,它工作了,所以我知道它工作了,现在我只需要找到这个链接,非常感谢您的关注。我正在使用WebClient,遇到了一些问题,但是添加UserAgent头对我来说完全不同。没想到。。。谢谢
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;
}
}