您的位置:首页 > Web前端 > Node.js

nodejs使用爬虫代理的方案

2019-03-05 17:41 134 查看

const http = require(“http”);
const url = require(“url”);

// 要访问的目标页面
const targetUrl = "http://httpbin.org/ip";

const urlParsed = url.parse(targetUrl);

// 代理服务器
const proxyHost = "t.16yun.cn";
const proxyPort = "36600";

// 生成一个随机 proxy tunnel
var seed = 1;
function random() {
var x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
}
const tunnel = random()*100;

// 代理验证信息
const proxyUser = "username";
const proxyPass = "password";

const base64    = new Buffer.from(proxyUser + ":" + proxyPass).toString("base64");

const options = {
host: proxyHost,
port: proxyPort,
path: targetUrl,
method: "GET",
headers: {
"Host": urlParsed.hostname,
"Proxy-Tunnel": tunnel,
"Proxy-Authorization" : "Basic " + base64
}
};

http.request(options, function (res) {
console.log("got response: " + res.statusCode);
res.pipe(process.stdout);
}).on("error", function (err) {
console.log(err);
}).end();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: