一提到爬虫,大多数同学都想到的是Python,Python 的优点大家都知道那就是高效率,从零到爬取数据估计半个小时就能动起来。不知道选择 Node.js人有多少,因为Node.js 更侧重于 io 处理,但其 Javascript 语言特性也能带来高效的开发体验。两者都有不错的异步性能, Python 3 之后已经原生支持协程, Node.js 更不用说了。
所以这两个用于爬虫,如果都熟练掌握,你会更倾向于哪一个?不过大家都对python熟悉的不能再熟悉了,所以今天我们就偏向于Node.js ,并简单的写个小爬虫程序,爬虫肯定是为了爬取数据信息,那首先我们就需要确定下我们的目标网站,这里我们就以获取微博热搜数据为需求。但是微博近来风控比较严,当然在访问过程中我们肯定会遇到网站反爬的,那么这时我们就需要加入代理ip来进行伪装了。这都是比较简单的操作,示例过程如下:
Plain Text
复制代码
const http = require("http");
const url = require("url");
// 要访问的目标页面
const targetUrl = "http://httpbin.org/ip";
const urlParsed = url.parse(targetUrl);
// 代理服务器(产品官网 www.16yun.cn)
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();
示例主要是以代理IP在程序里面的实现防过程为重点,每种语言代理IP的使用应该也有细微的差别,对其他语言感兴趣的可以私聊或直接搜索亿牛云获取更多详细的代码示例。