開始之前請先確保自己安裝了Node.js環境!!!!!!!!
1.在項目文件夾安裝兩個必須的依賴包
1 npm install superagent -S
SuperAgent(官網是這樣解釋的)
-----SuperAgent is light-weight progressive ajax API crafted for flexibility, readability, and a low learning curve after being frustrated with many of the existing request APIs. It also works with Node.js!
-----superagent 是一個輕量的,漸進式的ajax api,可讀性好,學習曲線低,內部依賴nodejs原生的請求api,適用於nodejs環境下
npm install cheerio -S
2.Cheerio
-----cheerio是nodejs的抓取頁面模塊,為服務器特別定制的,快速、靈活、實施的jQuery核心實現。適合各種Web爬蟲程序。相當於node.js中的jQuery
3.新建 crawler.js 文件
在里面輸入
1 //導入依賴包
2 const http = require("http");
3 const path = require("path"); 4 const url = require("url"); 5 const fs = require("fs"); 7 const superagent = require("superagent"); 8 const cheerio = require("cheerio"); 11 superagent 12 .get("https://www.zhipin.com/job_detail/?city=100010000&source=10&query=%E5%89%8D%E7%AB%AF")
13 .end((error, response) => { 14 //獲取頁面文檔數據 15 var content = response.text; 16 //cheerio也就是nodejs下的jQuery 將整個文檔包裝成一個集合,定義一個變量$接收 17 var $ = cheerio.load(content); 18 //定義一個空數組,用來接收數據 19 var result = []; 20 //分析文檔結構 先獲取每個li 再遍歷里面的內容(此時每個li里面就存放着我們想要獲取的數據) 21 $(".job-list li .job-primary").each((index, value) => { 22 //地址和類型為一行顯示,需要用到字符串截取 23 //地址 24 let address = $(value).find(".info-primary").children().eq(1).html(); 25 //類型 26 let type = $(value).find(".info-company p").html(); 27 //解碼 28 address = unescape(address.replace(/&#x/g, '%u').replace(/;/g, '')); 29 type = unescape(type.replace(/&#x/g, '%u').replace(/;/g, '')) 30 //字符串截取 31 let addressArr = address.split('<em class="vline"></em>'); 32 let typeArr = type.split('<em class="vline"></em>'); 33 //將獲取的數據以對象的形式添加到數組中 34 result.push({ 35 title: $(value).find(".name .job-title").text(), 36 money: $(value).find(".name .red").text(), 37 address: addressArr, 38 company: $(value).find(".info-company a").text(), 39 type: typeArr, 40 position: $(value).find(".info-publis .name").text(), 41 txImg: $(value).find(".info-publis img").attr("src"), 42 time: $(value).find(".info-publis p").text() 43 }); 44 // console.log(typeof $(value).find(".info-primary").children().eq(1).html()); 45 }); 46 //將數組轉換成字符串 47 result = JSON.stringify(result); 48 //將數組輸出到json文件里 刷新目錄 即可看到當前文件夾多出一個boss.json文件(打開boss.json文件,ctrl+A全選之后 ctrl+K,再Ctrl+F即可將json文件自動排版) 49 fs.writeFile("boss.json", result, "utf-8", (error) => { 50 //監聽錯誤,如正常輸出,則打印null 51 if (error == null) { 52 console.log("恭喜您,數據爬取成功!請打開json文件,先Ctrl+A,再Ctrl+K,最后Ctrl+F格式化后查看json文件(僅限Visual Studio Code編輯器)"); 53 } 54 }); 55 });
4.更改數據(如果是靜態頁面上面的操作基本上就已經完成了 直接node .\cralwer.js,但是現實中很多都不是)
1.在游覽器中輸入想要爬取的地址
例如:https://www.zhipin.com/job_detail/?city=100010000&source=10&query=%E5%89%8D%E7%AB%AF
2.進入控制台選中body copy element
3.在編輯器中粘貼即可
5.在服務器環境下運行這個網頁
7.復制這個地址欄地址
然后粘貼在文件 cralwer.js .get()中
8. 在終端中運行
node .\cralwer.js
最后 本文借鑒於https: //blog.csdn.net/twodogya/article/details/80204322