简体   繁体   中英

Puppeteer: get localStorage from a website

I need to take with Puppeteer all the data that a website saves: cookies and localStorage (for example after Login). I have read all Puppeteer documentation but I can not find anything about localStorage.

在此处输入图像描述

I can get cookies but I don't know to get localStorage. For example:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()
  await page.goto('https://www.twitter.com/')

  //
  // code for login
  //

  const returnedCookie = await page.cookies();  
  console.log(returnedCookie)
  // const localStorage = ??
  // console.log(localStorage)

  await browser.close()
})()

easier way that worked for me

const localStorage = await page.evaluate(() => Object.assign({}, window.localStorage));

I found the way:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()
  await page.goto('https://www.twitter.com/')

  //
  // code for login
  //

  const returnedCookie = await page.cookies();  
  console.log(returnedCookie)

  await page.waitFor( 10000 );
  const localStorageData = await page.evaluate(() => {
    let json = {};
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      json[key] = localStorage.getItem(key);
    }
    return json;
  });

  console.log(localStorageData)

  await browser.close()
})()

Guido's answer works but if you want to return just a single value (and not the whole Local/Session storage object) from local/session storage, then you can use:

const localStorage = await page.evaluate(() => localStorage.getItem("myKey"));

Note: If it's empty, it will return null .

Puppeteer 5.3.1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM