c# 中通过webdriver下载文件
string exportTarUrl = downloadUrl.Replace("export", "export_output");
string loginName = ConfigurationManager.AppSettings["loginname"];
string authorizationUrl = ConfigurationManager.AppSettings["authorizationUrl"];
string ShowChrome =ConfigurationManager.AppSettings["showChrome"];
if (bCheck)
{
return null;
}
string driverPath = AppDomain.CurrentDomain.BaseDirectory;
ChromeDriverService service = ChromeDriverService.CreateDefaultService(driverPath);
service.HideCommandPromptWindow = true;
var options = new ChromeOptions();
if ("0" == ShowChrome)
{
options.AddArgument("--window-position=-32000,-32000");
}
IWebDriver driver = new ChromeDriver(service, options);
Console.WriteLine($"Start to login {authorizationUrl}");
driver.Navigate().GoToUrl(authorizationUrl);
driver.FindElement(By.XPath("//*[@id='login_form']/div/button")).Click();
driver.FindElement(By.Name("loginfmt")).SendKeys(loginName);
driver.FindElement(By.Id("idSIButton9")).Click();
Thread.Sleep(20000);
driver.Navigate().GoToUrl(downloadUrl);
Console.WriteLine($"login {authorizationUrl} success");
driver.FindElement(By.XPath("//* [@id='content']/div[2]/section/article/div[2]/h2/ul")).Click();
Thread.Sleep(8*1000);
var client = new WebClient();
client.Headers[HttpRequestHeader.Cookie] = cookieString(driver);
string filename = string.Format("{0}.tar.gz", Guid.NewGuid());
string diretory = string.Format("{0}openedx", Path.GetTempPath());
if (!Directory.Exists(diretory))
{
Directory.CreateDirectory(diretory);
}
string filepath = Path.Combine(diretory, filename);
Console.WriteLine("start to download open_edx tar package and download url :"+exportTarUrl);
client.DownloadFile(exportTarUrl, filepath);
var resultExportTar = File.Open(filepath, FileMode.Open);
driver.Close();
Console.WriteLine("download open_edx tar package success");
string cmd = "taskkill /im chromedriver.exe /f";
string output = "";
CmdHelper.RunCmd(cmd, out output);
return resultExportTar;
}
catch (Exception ex)
{
log.ErrorFormat("Failed to ExportTarBySenium. Err: {0}", ex.ToString());
throw;
}
附件列表