N
N
nicolaa2021-04-25 11:39:35
Node.js
nicolaa, 2021-04-25 11:39:35

How to remember site authorization on nodejs?



I use nightmare to parse the site, but all information is given only after authorization

let cookie_ = fs.readFileSync("cookies.json");//Ищу фаил с сохраненными куками
cookie = JSON.parse(cookie_);//Превращаю в json

nightmare
.goto('https://site.ru/login')//Захожу на сайт
.cookies.set(cookie)//Подставляю куки из файла
.evaluate(function () {
    return document.querySelector('input[id="email"]');//Ищу поле для ввода почты
})
.then(function (page) {
    if(page) {//Проверяю есть ли поле для ввода почты
        f().then(function (cookies) {//Получаем результат из функции
            require('fs').writeFileSync(//И записываем в фаил
                'cookies.json',
                JSON.stringify(cookies)
            );
        })

    } else {
        console.log('Вы авторизированы');
    }
})
async function f() {//Вызываю функцию в случаи если мы не авторизированы
        return new Promise((resolve, reject) => {
            nightmare
                .goto('https://site.ru/login')
                .type('input[id="email"]', 'login')//Вводим почту
                .type('input[id="password"]', 'passord')//Вводим пароль
                .click('.btn.btn-danger')//Нажимаем на кнопку авторизации
                .wait(2000)//Ждем 2 секунды
                .cookies.get()//Получаем куки
                .then(resolve)

        });
    }


The file is created, cookies are written, but the next time you try to run the script, the authorization form still appears

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nicolaa, 2021-04-25
@nicolaa

Unfortunately, it was not possible to solve this problem through nightmare.
I solved it with the help of puppeteer
. Example - saving cookies to a file

const puppeteer = require('puppeteer')
const fs = require('fs');

(async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()

  await page.goto('https://github.com/login')

  await page.type('#login_field', process.env.GITHUB_USER)
  await page.type('#password', process.env.GITHUB_PWD)

  await page.waitForSelector('.js-cookie-consent-reject')
  await page.click('.js-cookie-consent-reject')
  await page.$eval('[name="commit"]', (elem) => elem.click())
  await page.waitForNavigation()

  const cookies = await page.cookies()
  const cookieJson = JSON.stringify(cookies)

  fs.writeFileSync('cookies.json', cookieJson)

  await browser.close()
})()

Reading cookies from a file
const puppeteer = require('puppeteer')
const fs = require('fs');

(async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()

  const cookies = fs.readFileSync('cookies.json', 'utf8')

  const deserializedCookies = JSON.parse(cookies)
  await page.setCookie(...deserializedCookies)

  await page.goto(`https://github.com/${process.env.GITHUB_USER}`)

  await browser.close()
})()

Article

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question