我正在尝试使用 Playwright 录制 HAR 文件。
根据文档,您需要做的就是传入RecordHarPath
并BrowserContextOptions
调用CloseAsync
.BrowserContext
使用 Firefox,这不会创建任何 HAR 文件。使用 Chromium,它会挂起CloseAsync
并且永远不会完成。
例如
static async Task Main()
{
var playwright = await Playwright.CreateAsync();
var currentDir = Directory.GetCurrentDirectory();
Console.WriteLine("Trying Firefox");
var firefox = await playwright.Firefox.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false});
await TryWith(firefox, Path.Combine(currentDir, "firefoxHar.har"));
Console.WriteLine("Trying Chromium");
var chromium = await playwright.Chromium.LaunchAsync(new BrowserTypeLaunchOptions { Headless = false });
await TryWith(chromium, Path.Combine(currentDir, "chromium.har"));
}
static async Task TryWith(IBrowser browser, string harPath)
{
var context = await browser.NewContextAsync(new BrowserNewContextOptions()
{
RecordHarPath = harPath
});
var page = await context.NewPageAsync();
await page.GotoAsync("https://www.microsoft.com");
var link = await page.QuerySelectorAsync("a#uhf-shopping-cart");
await link.ClickAsync();
Console.WriteLine("Closing Context");
await context.CloseAsync();
Console.WriteLine("Closing Browser");
await browser.CloseAsync();
}