我试图在 Puppetteer-Sharp 中设置一个 cookie,转到一个页面,并读取页面上一个元素的 innerHtml,但是,似乎从未设置过 cookie。如何在 Puppetetteer-Sharp 中正确设置 cookie?
public async Task<string> RenderPage(string baseUrl, string url, string cookieName, string cookieValue)
{
await new BrowserFetcher().DownloadAsync(BrowserFetcher.DefaultRevision);
using (var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = false }))
{
using (var page = await browser.NewPageAsync())
{
await page.SetCookieAsync(new CookieParam {
Name = cookieName,
Value = cookieValue,
Domain = baseUrl,
Url = baseUrl + url
});
await page.GoToAsync(baseUrl + url);
await page.WaitForSelectorAsync("table.summary-table");
var cookies = await page.GetCookiesAsync(baseUrl + url);
var element = await page.QuerySelectorAsync("html");
var text = await (await element.GetPropertyAsync("innerHTML")).JsonValueAsync<string>();
Console.WriteLine(text);
return text;
}
}
}
在 Chromium 开发控制台中,您可以看到该域没有 cookie:
从 Visual Studio 调试器中,可以看到 Puppeteer 认为页面上没有设置 cookie: