Nodejs爬蟲,使用cheerio+request+phantomjs實現超簡單爬蟲
之前寫過golang裡比較好用的爬蟲工具是 goquery[傳送門]
今天來介紹一下nodejs裡的爬蟲
建立專案
使用npm初始化一個nodejs專案
# 建立一個資料夾 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(); }) }
執行結果
原文連結: