我无法使用剧作家自动化从浏览器下载文件
我正在使用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;
}
这是一个简化的代码,模拟在C#中使用Playwright下载文件
此示例中使用Microsoft.Playwright NuGet扩展。
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);
}