-----superagent 是一個輕量的,漸進式的ajax api,可讀性好,學習曲線低,內部依賴nodejs原生的請求api,適用于nodejs環境下
npm install cheerio --save-dev
Cheerio
-----cheerio是nodejs的抓取頁面模塊,為服務器特別定制的,快速、靈活、實施的jQuery核心實現。適合各種Web爬蟲程序。相當于node.js中的jQuery
2.新建 crawler.js 文件
//導入依賴包 const http = require("http"); const path = require("path"); const url = require("url"); const fs = require("fs"); const superagent = require("superagent"); const cheerio = require("cheerio"); 3.看注釋啦(這里爬取的是boss直聘網站的數據) superagent .get("https://www.zhipin.com/job_detail/?city=100010000&source=10&query=%E5%89%8D%E7%AB%AF") .end((error,response)=>{ //獲取頁面文檔數據 var content = response.text; //cheerio也就是nodejs下的jQuery 將整個文檔包裝成一個集合,定義一個變量$接收 var $ = cheerio.load(content); //定義一個空數組,用來接收數據 var result=[]; //分析文檔結構 先獲取每個li 再遍歷里面的內容(此時每個li里面就存放著我們想要獲取的數據) $(".job-list li .job-primary").each((index,value)=>{ //地址和類型為一行顯示,需要用到字符串截取 //地址 let address=$(value).find(".info-primary").children().eq(1).html(); //類型 let type=$(value).find(".info-company p").html(); //解碼 address=unescape(address.replace(//g,'%u').replace(/;/g,'')); type=unescape(type.replace(//g,'%u').replace(/;/g,'')) //字符串截取 let addressArr=address.split('<em class="vline"></em>'); let typeArr=type.split('<em class="vline"></em>'); //將獲取的數據以對象的形式添加到數組中 result.push({ title:$(value).find(".name .job-title").text(), money:$(value).find(".name .red").text(), address:addressArr, company:$(value).find(".info-company a").text(), type:typeArr, position:$(value).find(".info-publis .name").text(), txImg:$(value).find(".info-publis img").attr("src"), time:$(value).find(".info-publis p").text() }); // console.log(typeof $(value).find(".info-primary").children().eq(1).html()); }); //將數組轉換成字符串 result=JSON.stringify(result); //將數組
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com