Reputation: 1
I am not able to download file from browser using playwright automation.
I am using C# language for automation.
I have created browser context with acceptDownload and also provided directory path for file download. Basically code is stuck at RunAndWaitForDownloadAsync method and noting is happening after that.
Please find below which I have used to download file.
//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;
}
Upvotes: 0
Views: 2590
Reputation: 2703
This is simplified code simulating downloading files using Playwright in C#.
Microsoft.Playwright NuGet extension is used in this example.
private async void DownloadTest()
{
const string url = "https://file-examples.com/index.php/sample-documents-download/sample-doc-download/";
var PlayWright = await Playwright.CreateAsync();
BrowserTypeLaunchOptions browserLaunchOptions = new BrowserTypeLaunchOptions() { Headless = false, Devtools = true };
var Browser = await PlayWright.Chromium.LaunchAsync(browserLaunchOptions);
BrowserNewContextOptions browserContextOptions = new BrowserNewContextOptions() { AcceptDownloads = true };
var Context = await Browser.NewContextAsync(browserContextOptions);
var Page = await Context.NewPageAsync();
Page.Download += Page_Download;
await Page.GotoAsync(url, new PageGotoOptions() { WaitUntil = WaitUntilState.NetworkIdle });
await Page.EvaluateAsync("document.getElementsByTagName('table')[0].getElementsByTagName('a')[0].click();");
}
// Download files
private async void Page_Download(object sender, IDownload e)
{
string fileName = e.SuggestedFilename;
await e.SaveAsAsync(e.SuggestedFilename);
}
Upvotes: 0