puppeteer注入cookie然后访问页面

var puppeteer = require('puppeteer');
const devices = require('puppeteer/DeviceDescriptors');
const iphone = devices["iPhone 6"]
const path = require('path');
const pathToExtension = path.join(__dirname, './chrome-mac/Chromium.app/Contents/MacOS/Chromium');

const conf = {
    headless: false,
    executablePath: pathToExtension,
    defaultViewport: {
        width: 1300,
        height: 900
    }
}
let cookieString = `
BDUSS=TNJUFJDbTdoAAAC8DzIkbXV6aWNvNDI1GGGGGGGGGGGGGAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAB1TLF0dUyxdS;
`
const addCookies = async (cookies_str, page, domain) => {
    let cookies = cookies_str.split(';').map(
        pair => {
        let name = pair.trim().slice(0, pair.trim().indexOf('='));
        let value = pair.trim().slice(pair.trim().indexOf('=') + 1);
        return {name, value, domain}
    });
    await Promise.all(cookies.map(pair => {
        console.log(pair);
        return page.setCookie(pair)
    }))
};
(async () => {
    const browser = await puppeteer.launch(conf);

    const page = await browser.newPage();
    ps= await browser.pages()
    await ps[0].close()

    //await page.setUserAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Safari/537.36");
    await page.emulate(iphone)
    await page.evaluateOnNewDocument(() => {
        delete navigator.__proto__.webdriver;
    });
    await page.evaluateOnNewDocument(() => {
        Object.defineProperty(navigator, 'plugins', {
            get: () => [1, 2, 3, 4, 5],
        });
    });
    await page.evaluateOnNewDocument(() => {
        Object.defineProperty(navigator, 'languages', {
            get: () => ['en-US', 'en'],
        });
    });
    await page.evaluateOnNewDocument(() => {
        Object.defineProperty(navigator, 'platform', {
            get: () => "Linux armxxxxx",
            configurable: true
        });
    });

    await page.evaluateOnNewDocument(() => {
        window.navigator.chrome = {
            runtime: {},
            getUserMedia: {},
        };
    });
    await addCookies(cookieString, page, 'www.baidu.com');

    await page.goto(`https://www.baidu.com`);

})()
posted @ 2019-07-26 15:30  公众号python学习开发  阅读(7147)  评论(0编辑  收藏  举报