Node.js 抓取(爬蟲)別人的接口(get、post)獲取數據 生成 Excel

const xlsx = require('node-xlsx')//xlsx 庫
const fs =  require('fs') //文件讀寫庫
const request = require("request");//request請求庫
let data = [] // 把這個數組寫入excel   
request({
    url: "https://qudao.youzan.com/resource/department/list",//你要請求的地址
    method: "post",//請求方法 post get
    json: true,
    headers: {
        "content-type": "application/json",
        "Cookie":""//如果攜帶了cookie
    },
    body: {"page":1,"pageSize":3,"sortAsc":false,"sortKey":"lastVisitTime","prodLineId":2},//這裏是post 傳的參數 如果是get 方法在url上拼接就好了
}, function (error, response, body) {
    if (!error && response.statusCode == 200) {
        // console.log(body)
        const rows = body.data.items
        let title = ['address','alias','bindDisplayName','boundTime','customerAlias','customerId','customerName','infoSourceName'
        ,'predictedReleaseReason','region','unboundTime','mobile','name']//設置表頭
        data.push(title) // 添加完表頭 下面就是添加真正的內容了
        rows.forEach((e) => {
            let arrInner = []
            arrInner.push(e.address)
            arrInner.push(e.alias)
            arrInner.push(e.bindDisplayName)
            arrInner.push(e.boundTime)
            arrInner.push(e.customerAlias)
            arrInner.push(e.customerId)
            arrInner.push(e.customerName)
            arrInner.push(e.infoSourceName)
            arrInner.push(e.predictedReleaseReason)
            arrInner.push(e.region)
            arrInner.push(e.unboundTime)   
            data.push(arrInner)
        });
        writeXls(data)
    }
}); 



// 寫xlsx文件
function writeXls(datas) {
    let buffer = xlsx.build([
    {
        name:'sheet1',
        data:datas
    }
    ]);
    fs.writeFileSync('./data.xlsx',buffer,{'flag':'w'});//生成excel data是excel的名字
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章