如何使用Puppeteer获取网站的第三方cookie?
对于第一方cookie,我知道可以使用以下代码:
await page.cookies()
如何使用Puppeteer获取网站的第三方cookie?
对于第一方cookie,我知道可以使用以下代码:
await page.cookies()
我想知道答案,所以我找到了一个解决方案,它适用于当前版本的Chromium 75.0.3765.0和puppeteer 1.15.0(更新于2019年5月2日)。
使用内部puppeteerpage._client
方法,我们可以直接使用Chrome DevTools Protocol:
(async() => {
const browser = await puppeteer.launch({});
const page = await browser.newPage();
await page.goto('https://stackoverflow.com', {waitUntil : 'networkidle2' });
// Here we can get all of the cookies
console.log(await page._client.send('Network.getAllCookies'));
})();
返回的对象中包含了 google.com 和 imgur.com 的 cookie,这些 cookie 通常不能通过正常的浏览器 JavaScript 获取:
target.createCDPSession()
在 页面目标 上创建一个 Chrome DevTools Protocol 会话。然后,您可以发送 Network.getAllCookies
来获取所有浏览器 cookie 的列表。
page.cookies()
函数仅返回当前 URL 的 cookie。因此,我们可以将所有浏览器 cookie 中当前页面的 cookie 过滤掉,从而获得仅包含第三方 cookie 的列表。const client = await page.target().createCDPSession();
const all_browser_cookies = (await client.send('Network.getAllCookies')).cookies;
const current_url_cookies = await page.cookies();
const third_party_cookies = all_browser_cookies.filter(cookie => cookie.domain !== current_url_cookies[0].domain);
console.log(all_browser_cookies); // All Browser Cookies
console.log(current_url_cookies); // Current URL Cookies
console.log(third_party_cookies); // Third-Party Cookies
const browser = await puppeteer.launch({});
const page = await browser.newPage();
await page.goto('https://www.stackoverflow.com/', {waitUntil : 'networkidle0' });
// networkidle2, domcontentloaded, load are the options for wai until
// Here we can get all of the cookies
var content = await page._client.send('Network.getAllCookies');
console.log(JSON.stringify(content, null, 4));