您如何在Puppetteer-Sharp中设置Cookie?

时间:2019-06-14 18:01:47

标签: c# puppeteer-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: no cookies

从Visual Studio调试器中,您可以看到Puppeteer认为页面上没有设置cookie:

no cookies on the page

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

通过执行以下操作,我可以使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;
        }
      }
    }

虽然不确定我上面的代码为何不起作用,但是...