如何使用node.js抓取需要身份验证的站点

How can I scrape sites that require authentication using node.js?

本文关键字:身份验证 站点 抓取 何使用 node js      更新时间:2023-09-26

我看到了许多教程,解释了如何使用node.js.抓取不需要身份验证/登录的公共网站

有人能解释一下如何使用node.js抓取需要登录的网站吗?

使用Mikeal的请求库,您需要启用这样的cookie支持:

var request = request.defaults({jar: true})

因此,您首先应该在该站点上创建一个用户名(手动),并在向该站点发出POST请求时将用户名和密码作为params传递。之后,服务器将使用请求会记住的cookie进行响应,这样您就可以访问需要登录该网站的页面。

注意:如果在登录页面上使用类似reCaptcha的东西,这种方法就不起作用。

我已经使用NodeJs Scrapers工作了两年多了

我可以告诉你,在处理登录和身份验证时,最好的选择是不使用直接请求

这是因为你只是在构建手动请求上浪费时间,而且速度慢得多,

相反,使用通过API控制的高级浏览器,如Puppeteer或NightmareJs

我有一个关于如何开始使用Puppeteer的良好入门和深入指南,我相信它会有所帮助!

或使用超级代理:

var superagent = require('superagent')
var agent = superagent.agent();

agent是一个持久的浏览器,它将处理获取和设置cookie、referers等。正常情况下只有agent.getagent.post()

您可以从需要身份验证的站点抓取数据,如csrf令牌

对每个请求使用cookie,如下所示:

var j = request.jar(); // this is to set the jar of request for session and cookie persistence
request = request.defaults({ jar: j }); //here we are setting the default cookies of request

以下是进一步详细说明的小代码:

var express = require('express');
var bodyParser = require('body-parser');
var querystring = require('querystring');
var request = require('request'); //npm request package to send a get and post request to a url
const cheerio = require('cheerio'); //npm package used for scraping content from third party sites
var cookieParser = require('cookie-parser')
var http = require('http');
var app = express();
app.use(cookieParser());
var _csrf; //variable to store the _csrf value to be used later
app.use(bodyParser.json());
var html = '';
var j = request.jar(); // this is to set the jar of request for session and cookie persistence
request = request.defaults({ jar: j }); //here we are setting the default cookies of request

//___________________API CALL TO VERIFY THE GMS NUMBER_______________________
app.get('/check', function(req, response) {
    var schemeId = null;
    if (req.query.schemeId) {
        schemeId = req.query.schemeId;
        console.log(schemeId);
    } else {
        response.send('false');
        response.end();
    }
    getCsrfValue(function(err, res) {
        if (!err) {
            _csrf = res;
            console.log(_csrf);
            request.post({
                headers: {
                    'Authorization': '',
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                uri: 'https://www.xyz.site',
                body: "schemeId=" + schemeId + "&_csrf=" + _csrf
            }, function(err, res, body) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("body of post: " + res.body);
                    const $ = cheerio.load(body.toString());
                    var txt = $('.schemeCheckResult').text();
                    console.log(txt);
                    if (txt) {
                        response.send('true');
                    } else {
                        response.send('false');
                    }
                    html += body;
                }
            });
        } else {
            response.send(err);
        }
    })

});
//______________FUNCTION TO SCRAPE THE CSRF TOKEN FROM THE SITE____________
function getCsrfValue(callback) {
    request.get({
        headers: {
            'Authorization': '',
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        uri: 'https://www.xyz.site'
    }, function(err, res, body) {
        if (err) {
            return callback(err);
        } else {
            const $ = cheerio.load(body.toString());
            var txt = $('input[name=_csrf]').val();
            _csrf = txt;
            return callback(null, _csrf);
        }
    });
}
module.exports = app;