我无法使用剧作家自动化从浏览器下载文件。
我正在使用 C# 语言进行自动化。我已经使用 acceptDownload 创建了浏览器上下文,还提供了文件下载的目录路径。基本上代码被卡在 RunAndWaitForDownloadAsync 方法上,并且在那之后发生了注意事项。请在下面找到我用来下载文件的内容。
//While creating browser context
var playwright = await Playwright.CreateAsync();
var browser = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions()
{
Headless = false,
DownloadsPath = Directory.GetCurrentDirectory()
});
var context = await browser.NewContextAsync(new BrowserNewContextOptions() { AcceptDownloads = true });
//For file download used below code.
var download = await _page.RunAndWaitForDownloadAsync(async () =>
{
await _page.ClickAsync("#btnId");
}, new PageRunAndWaitForDownloadOptions() { Timeout = 10000 });
var tmpDir = Directory.GetCurrentDirectory();
string userPath = Path.Combine(tmpDir, "download.docx");
await download.SaveAsAsync(userPath);
string path = await download.PathAsync();
Assert.True(new FileInfo(path).Exists);
//One more option tried as below.
var downloadTask = _page.WaitForDownloadAsync();
await WhenAll(downloadTask, _page.ClickAsync("#btnSubmission")).ConfigureAwait(false);
var download = downloadTask.Result;
var tmpDir = Directory.GetCurrentDirectory();
string userPath = Path.Combine(tmpDir, "download.docx");
await download.SaveAsAsync(userPath);
string path = await download.PathAsync();
Assert.True(new FileInfo(path).Exists);
//Supporting method
public static async Task<T> WhenAll<T>(Task<T> task1, Task task2)
{
await Task.WhenAll(task1, task2).ConfigureAwait(false);
return task1.Result;
}