使用 Selenium WebDriver 在自定义路径下载文件
Download file at custom path using Selenium WebDriver
我是 selenium 的新手,我想在特定的自定义文件夹中下载带有 selenium chrome 网络驱动程序的文件。默认情况下,文件在浏览器指定的下载路径中下载。有人建议在 C# Selenium 的自定义路径中下载文件的最佳解决方案。
希望对您有所帮助!!
var chromeOptions = new ChromeOptions();
chromeOptions.AddUserProfilePreference("download.default_directory", "Your_Path");
chromeOptions.AddUserProfilePreference("intl.accept_languages", "nl");
chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");
var driver = new ChromeDriver("Driver_Path", chromeOptions);
您需要修改一下才能将文件下载到指定位置。
选项 1:使用第三方工具,如 AutoIt,它可以与 Windows 弹出窗口交互,您可以使用它指定路径。
选项 2:编写一个可以使用 API 进行下载的自定义方法。
var downloadDocLink = webDriver.FindElement(By.XPath("{}")).GetAttribute("onclick");
string toBeSearched = "{string}"; //this string needs to be trimmed from the url
string downloadUrl = downloadDocLink.Substring(downloadDocLink.IndexOf(toBeSearched) + toBeSearched.Length);
var data = webDriver.DownloadByApiCall(downloadUrl);
var fileName = webDriver.FindElement(By.XPath("{Xpath}")).Text;
//Save result of report api call to file
var val = ConfigurationManager.AppSettings["OutputPath"];
var path = Environment.ExpandEnvironmentVariables(val);
var filePath = Path.Combine(path, fileName);
var dir = Path.GetDirectoryName(path);
Console.WriteLine($"Saving file with {data.Length} bytes to {path}.");
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
File.WriteAllBytes(filePath, data);
//Ensure file was downloaded
var exists = webDriver.FileExistsSpinWait(filePath);
Assert.IsTrue(exists, $"The downloaded report is not present in the download folder: \n{filePath}");
//Remove file and ensure deleted
File.Delete(filePath);
Assert.IsFalse(File.Exists(filePath));
通过API调用
下载的辅助方法
public static byte[] DownloadByApiCall(this IWebDriver driver, string apiCall)
{
var uri = new Uri(driver.Url);
var path = $"{url}/{apiCall}";
byte[] data = null;
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(path);
webRequest.CookieContainer = new CookieContainer();
foreach (var cookie in driver.Manage().Cookies.AllCookies)
webRequest.CookieContainer.Add(new System.Net.Cookie(cookie.Name, cookie.Value, cookie.Path, string.IsNullOrWhiteSpace(cookie.Domain) ? uri.Host : cookie.Domain));
var webResponse = (HttpWebResponse)webRequest.GetResponse();
var ms = new MemoryStream();
var responseStream = webResponse.GetResponseStream();
responseStream.CopyTo(ms);
data = ms.ToArray();
responseStream.Close();
webResponse.Close();
}
catch (WebException webex)
{
var errResp = webex.Response;
using (var respStream = errResp.GetResponseStream())
{
var reader = new StreamReader(respStream);
Assert.Fail($"Error getting file from the server({webex.Status} - {webex.Message}): {reader.ReadToEnd()}.");
}
}
return data;
}
这对我有用,它断言下载是否成功并且可以重新运行,并且我们最终会删除该文件。希望这对您有所帮助!
我是 selenium 的新手,我想在特定的自定义文件夹中下载带有 selenium chrome 网络驱动程序的文件。默认情况下,文件在浏览器指定的下载路径中下载。有人建议在 C# Selenium 的自定义路径中下载文件的最佳解决方案。
希望对您有所帮助!!
var chromeOptions = new ChromeOptions();
chromeOptions.AddUserProfilePreference("download.default_directory", "Your_Path");
chromeOptions.AddUserProfilePreference("intl.accept_languages", "nl");
chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");
var driver = new ChromeDriver("Driver_Path", chromeOptions);
您需要修改一下才能将文件下载到指定位置。 选项 1:使用第三方工具,如 AutoIt,它可以与 Windows 弹出窗口交互,您可以使用它指定路径。 选项 2:编写一个可以使用 API 进行下载的自定义方法。
var downloadDocLink = webDriver.FindElement(By.XPath("{}")).GetAttribute("onclick");
string toBeSearched = "{string}"; //this string needs to be trimmed from the url
string downloadUrl = downloadDocLink.Substring(downloadDocLink.IndexOf(toBeSearched) + toBeSearched.Length);
var data = webDriver.DownloadByApiCall(downloadUrl);
var fileName = webDriver.FindElement(By.XPath("{Xpath}")).Text;
//Save result of report api call to file
var val = ConfigurationManager.AppSettings["OutputPath"];
var path = Environment.ExpandEnvironmentVariables(val);
var filePath = Path.Combine(path, fileName);
var dir = Path.GetDirectoryName(path);
Console.WriteLine($"Saving file with {data.Length} bytes to {path}.");
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
File.WriteAllBytes(filePath, data);
//Ensure file was downloaded
var exists = webDriver.FileExistsSpinWait(filePath);
Assert.IsTrue(exists, $"The downloaded report is not present in the download folder: \n{filePath}");
//Remove file and ensure deleted
File.Delete(filePath);
Assert.IsFalse(File.Exists(filePath));
通过API调用
下载的辅助方法public static byte[] DownloadByApiCall(this IWebDriver driver, string apiCall)
{
var uri = new Uri(driver.Url);
var path = $"{url}/{apiCall}";
byte[] data = null;
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(path);
webRequest.CookieContainer = new CookieContainer();
foreach (var cookie in driver.Manage().Cookies.AllCookies)
webRequest.CookieContainer.Add(new System.Net.Cookie(cookie.Name, cookie.Value, cookie.Path, string.IsNullOrWhiteSpace(cookie.Domain) ? uri.Host : cookie.Domain));
var webResponse = (HttpWebResponse)webRequest.GetResponse();
var ms = new MemoryStream();
var responseStream = webResponse.GetResponseStream();
responseStream.CopyTo(ms);
data = ms.ToArray();
responseStream.Close();
webResponse.Close();
}
catch (WebException webex)
{
var errResp = webex.Response;
using (var respStream = errResp.GetResponseStream())
{
var reader = new StreamReader(respStream);
Assert.Fail($"Error getting file from the server({webex.Status} - {webex.Message}): {reader.ReadToEnd()}.");
}
}
return data;
}
这对我有用,它断言下载是否成功并且可以重新运行,并且我们最终会删除该文件。希望这对您有所帮助!