你如何在 Puppeteer-Sharp 中设置 cookie?

How do you set a cookie in Puppetteer-Sharp?

我试图在 Puppetteer-Sharp 中设置一个 cookie,转到一个页面,并读取页面上某个元素的 innerHtml,但是,似乎从未设置过 cookie。如何在 Puppetteer-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:

我可以通过执行以下操作让 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.GoToAsync(baseUrl);
          await page.SetCookieAsync(new CookieParam { 
            Name = cookieName, 
            Value = cookieValue, 
          });
          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;
        }
      }
    }

不知道为什么我上面的代码不起作用,但是...

你必须小心你的 domain 属性。如果它无效,它将被忽略。 对于我在那里看到的。当预期 yourdomain.com 时,您可能会设置类似 http://www.yourdomain.com 的内容。