Node.jsでウェブサイトを巡回してダウンロードするコードで 「$ is not a function」というエラーが出ます。
$("a").each(function(idx){
で発生しています。
解消方法をご教授願います。
var client = require('cheerio-httpcli'); var request = require('request'); var URL = require('url'); var fs = require('fs'); var path = require('path'); var LINK_LEVEL = 3; var TARGET_URL ="https://qiita.com/"; var list = {}; downloadRec(TARGET_URL, 0); function downloadRec(url, level){ if(level >= LINK_LEVEL) return; if(list[url]) return; list[url] = true; var us = TARGET_URL.split("/"); us.pop(); var base = us.join("/"); if(url.indexOf(base) < 0) return; client.fetch(url, {}, function(err, $, res){ $("a").each(function(idx){ var href = $(this).attr('href'); if(!href) return; href = URL.resolve(url, href); href = href.replace(/\#.+$/, ""); downloadRec(href, level + 1); }); if(url.substr(url.length - 1, 1) == '/'){ url += 'index.html'; } var savepath = url.split("/").slice(2).join("/"); checkSaveDir(savepath); console.log(savepath); fs.writeFileSync(savepath, $.html()); }); } function checkSaveDir(fname){ var dir = path.dirname(fname); var dirlist = dir.split("/"); var p = ""; for(var i in dirlist){ p += dirlist[i] + "/"; if(!fs.existsSync(p)){ fs.mkdirSync(p); } } }
エラーコード
TypeError: $ is not a function at Object.callback (/home/test/test21.js:23:5) at Object.fail (/home/test/node_modules/cheerio-httpcli/lib/client.js:90:22) at Object.<anonymous> (/home/test/node_modules/cheerio-httpcli/lib/client.js:254:14) at Object.<anonymous> (/home/test/node_modules/cheerio-httpcli/lib/client.js:184:11) at self.callback (/home/test/node_modules/request/request.js:185:22) at emitOne (events.js:116:13) at Request.emit (events.js:211:7) at Request.onRequestError (/home/test/node_modules/request/request.js:881:8) at emitOne (events.js:121:20) at ClientRequest.emit (events.js:211:7)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。