就目前反爬虫的手段,使用代理ip来规避的做法用nodejs具体要怎么做?

首先要说明一点,node-proxy-server 链接,适用于普通页面开发,配置简单,node 命令启动、支持跨域。

接着我们往下看:

1.配置

配置接口地址的拦截,以及代理接口的地址。

let conifg = {
    '/xxxx1': { // 需要拦截的本地请求路径
        target: 'http://xxxxxxxx.com', // 代理地址
        port: 80, // 端口,默认80,某些地址可能是8080
    },
    '/xxxx2': { 
        target: 'http://xxxxxxxx.com', 
        port: 80,
    }
    // ...other path
};

2.中间代理服务器

主要利用nodejs的 http 和 fs模块,创建一个中间服务器,接受页面请求,再通过中间服务器去请求真实接口,返回数据。

let http = require('http');
let fs = require('fs');
// 创建中间代理层http服务
let app = http.createServer(function (request, response) {
	// 主要逻辑:
	// 1.拦截请求配置的路径 if(hasProxy(url, request, response))
	// 2.普通请求,直接通过
});

3.拦截请求,转发请求

根据配置中的设定的拦截路径,拦截请求,并且转发到真实地址中。

// 判断是否存在代理地址
function hasProxy(url, request, response) {
    for (const key in conifg) { // 如果存在多个拦截路径
        const { target, port } = conifg[key];
        let info = target.split('//');
        let opts = { // 请求参数
            protocol: info[0],
            host: info[1],
            port: port || 80,
            method: request.method,
            path: url,
            json: true,
            headers: {}
        }
        proxy(opts, request, response);
        return true;
    }
    return false;
}

// 代理转发
function proxy(opts, request, response) {
    // 请求真实代理接口
    var proxyRequest = http.request(opts, function (proxyResponse) {
        // 代理接口返回数据,写入本地response
        proxyResponse.on('data', function (chunk) {
            response.write(chunk, 'binary');
        });
        // 代理接口结束,通知本地response结束
        proxyResponse.on('end', function () {
            response.end();
        });
        response.writeHead(proxyResponse.statusCode, proxyResponse.headers);
    });

    // 本地接口数据传输,通知代理接口请求
    request.on('data', function (chunk) {
        proxyRequest.write(chunk, 'binary');
    });

    // 本地请求结束,通知代理接口请求结束
    request.on('end', function () {
        proxyRequest.end();
    });
}

4.普通资源请求

非拦截请求,直接通过。

// 普通请求和资源加载
fs.readFile(__dirname + url, function (err, data) {
    if (err) {
        console.log('请求失败', err);
    } else {
        response.end(data);
    }
});

5.建议

爬虫目前的反扒机制,总的来说还是要让作业的时候,让自己看起来是个正常的用户访问,不然都白瞎。

综合对比的话,会建议你去使用代理厂商的产品,而且现在很多厂商都有提供测试,与其听别人说,不如自己实测一番。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值