Вы не можете переключаться без головы на лету. Но вы можете поделиться логином, используя куки и setCookie , если хотите.
Мы создадим простой класс для поддержания чистоты кода (или я верю в это для работы такого типа, поскольку они обычно становятся большими позже). Вы можете сделать это без всей этой сложности, хотя. Кроме того, убедитесь, что файлы cookie сериализованы. Не передавайте массив в функцию setCookie.
Будет три основных функции.
1. init()
Для создания объекта страницы. Главным образом, чтобы убедиться, что версия без заголовка и заголовка имеет похожий стиль просмотра, тот же пользовательский агент и т. Д. Обратите внимание, я не включил код для установки пользовательских агентов, он просто показывает концепцию.
async init(headless) {
const browser = await puppeteer.launch({
headless
});
const page = await browser.newPage();
// do more page stuff before loading, ie: user agent and so on
return {
page,
browser
};
}
2. getLoginCookies()
Пример того, как вы можете получить куки из браузера.
// will take care of our login using headful
async getLoginCookies() {
const {
page,
browser
} = await this.init(false)
// asume we load page and login here using some method
// and the website sets some cookie
await page.goto('http://httpbin.org/cookies/set/authenticated/true')
// store the cookie somewhere
this.cookies = await page.cookies() // the cookies are collected as array
// close the page and browser, we are done with this
await page.close();
await browser.close();
return true;
}
Вам не понадобится такая функция, если вы можете предоставить куки вручную. Вы можете использовать EditThisCookie или любой инструмент для редактирования файлов cookie. Вы получите массив всех файлов cookie для этого сайта. Вот как вы можете это сделать,
3. useHeadless()
Пример того, как вы можете установить куки в браузере.
// continue with our normal headless stuff
async useHeadless() {
const {
page,
browser
} = await this.init(true)
// we set all cookies we got previously
await page.setCookie(...this.cookies) // three dots represents spread syntax. The cookies are contained in a array.
// verify the cookies are working properly
await page.goto('http://httpbin.org/cookies');
const content = await page.$eval('body', e => e.innerText)
console.log(content)
// do other stuff
// close the page and browser, we are done with this
// deduplicate this however you like
await page.close();
await browser.close();
return true;
}
4. Создание нашего собственного удивительного экземпляра кукловода
// let's use this
(async () => {
const loginTester = new myAwesomePuppeteer()
await loginTester.getLoginCookies()
await loginTester.useHeadless()
})()
Полный код
Пройдите по коду, чтобы лучше его понять. Это все прокомментировано.
const puppeteer = require('puppeteer');
class myAwesomePuppeteer {
constructor() {
// keeps the cookies on the class scope
this.cookies;
}
// creates a browser instance and applies all kind of setup
async init(headless) {
const browser = await puppeteer.launch({
headless
});
const page = await browser.newPage();
// do more page stuff before loading, ie: user agent and so on
return {
page,
browser
};
}
// will take care of our login using headful
async getLoginCookies() {
const {
page,
browser
} = await this.init(false)
// asume we load page and login here using some method
// and the website sets some cookie
await page.goto('http://httpbin.org/cookies/set/authenticated/true')
// store the cookie somewhere
this.cookies = await page.cookies()
// close the page and browser, we are done with this
await page.close();
await browser.close();
return true;
}
// continue with our normal headless stuff
async useHeadless() {
const {
page,
browser
} = await this.init(true)
// we set all cookies we got previously
await page.setCookie(...this.cookies)
// verify the cookies are working properly
await page.goto('http://httpbin.org/cookies');
const content = await page.$eval('body', e => e.innerText)
console.log(content)
// do other stuff
// close the page and browser, we are done with this
// deduplicate this however you like
await page.close();
await browser.close();
return true;
}
}
// let's use this
(async () => {
const loginTester = new myAwesomePuppeteer()
await loginTester.getLoginCookies()
await loginTester.useHeadless()
})()
Вот результат,
➜ node app.js
{
"cookies": {
"authenticated": "true"
}
}
Короче говоря,
- Вы можете использовать функцию
cookies
для получения файлов cookie.
- Вы можете использовать такие расширения, как Редактировать этот файл cookie , чтобы получать файлы cookie из вашего обычного браузера.
- Вы можете использовать
setCookie
, чтобы установить любой тип файлов cookie, которые вы получаете из браузера.