之前写过 golang 里比较好用的爬虫工具是 goquery[传送门]
今天来介绍一下 Node.JS 里的爬虫
创建项目
使用 NPM 初始化一个 Node.JS 项目
- # 创建一个文件夹 crawling
- mkdir crawling
- # 进入文件夹并初始化
- cd crawling
- NPM init
安装依赖
yarn add cheerio request iconv-lite
cheerio 像 jQuery 一样用来解析网页的
request http 请求的工具
iconv-lite request 默认编码是 utf-8, 如果网页不是 utf-8 编码, 可以用来转码
封装一下 request
- var request = require('request');
- var iconv = require('iconv-lite');
- module.exports = function(url, method, encoding, callback) {
- request({
- url: url,
- method: method,
- encoding: null,
- // proxy: 'http://127.0.0.1:1087',
- headers: {
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) ApplewebKit/537.36 (Khtml, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
- }
- }, function(err, res, body) {
- body = iconv.decode(body, encoding);
- if (err) {
- console.log(err);
- } else {
- callback(body);
- }
- })
- }
开始爬取
- var request = require('./request');
- var cheerio = require('./cheerio');
- function fetch() {
- request('https://cnodejs.org/', 'get', 'utf-8', function(body) {
- var $ = cheerio.load(body);
- $('#topic_list').find('.cell').each(function(i, v) {
- var title = $(v).find('.topic_title').text();
- var href = 'https://cnodejs.org' + $(v).find('.topic_title').attr('href');
- console.log(title, href);
- })
- })
- }
运行结果
抓取网站是 JS 渲染的
现在前端这么流行, 很多网站都是用 JS 框架写的了, 这导致页面都是用 JS 渲染的, 普通的 http 请求拿到的只是 HTML 页面, 它不会执行 JS, 所以也就没有内容了, 下面介绍一下用 phantomjs 来抓取 JS 渲染的网页内容
这里用网易新闻手机版的, 打开链接 https://3g.163.com/touch/news/ 然后查看页面源代码, 可以看到 body 里是没有内容的
安装依赖
- yarn add phantom
- var phantom = require('phantom');
- function news() {
- var sitepage, phInstance;
- phantom.create()
- .then(function (instance) {
- phInstance = instance;
- return instance.createPage();
- }).then(function (page) {
- sitepage = page;
- return page.open('https://3g.163.com/touch/news/');
- }).then(function (status) {
- return sitepage.property('content');
- }).then(function (content) {
- var $ = cheerio.load(content);
- $(".recommend-list>article").each(function (i, v) {
- var title = $(v).find('.title').text();
- var href = $(v).find('a').attr('href');
- console.log(title, href);
- });
- }).then(function() {
- sitepage.close();
- phInstance.exit();
- }).catch(function (err) {
- phInstance.exit();
- })
- }
运行结果
来源: http://www.tuicool.com/articles/Ybm6Vrz