0

我试图在 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:

页面上没有 cookie

4

2 回答 2

2

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

于 2019-06-14T18:56:14.407 回答
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;
        }
      }
    }

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

于 2019-06-14T18:25:27.070 回答