An example of front-end spider

初衷

由于老婆是一個追求極致高效(看她工作辛苦??)工作的新媒體運營,于是請求我看能不能幫她簡化流程。作為一名愛老婆的前端攻城獅,這怎么能難得到我。三下五除二(還是查了不少網(wǎng)上的代碼,畢竟外號:代碼搬運工嘛)就擼出了下面的代碼。

代碼解釋

原本打算用后端node爬取的,但研究了一番后發(fā)現(xiàn),不能滿足夫人翻頁的需求,于是采用前端爬取的方案,雖然多了一些體力活,但相比原先的純手工打造還是進化了不知多少個世紀(嘿嘿??)呢!
代碼中運用到了jquery,ES6的寫法。

Talk is cheap,show me the code!

// 1 step
const script = document.createElement("script");
script.src = "https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js";
const s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(script, s);

// 2 step
let arr = [],
    page = 2,
    sequence = 1;

const currentCrawl = () => {
    $('.figures_list li').each(function (index, item) {
        let title = $(this).find('strong a').text(),
            reading = $(this).find('.figure_info .info_inner').text(),
            time = $(this).find('.figure_info .figure_info_time').text();
        if (reading.includes('萬')) {
            reading = reading.replace('萬', '') * 10000;
        }
        arr.push({'id': sequence, 'title': title, 'reading': reading, 'time': time});
        sequence++;
    });
    console.log(`爬取第${page - 1}頁成功,正在跳轉(zhuǎn)第${page}頁`);
    $('.page_next')[0].click();
    page++
};

const tableToExcel = () => {
    console.log(`正在導出數(shù)據(jù)`);
    //列標題,逗號隔開,每一個逗號就是隔開一個單元格
    let str = `序號,標題,瀏覽量,時間\n`;
    //增加\t為了不讓表格顯示科學計數(shù)法或者其他格式
    for (let i = 0; i < arr.length; i++) {
        for (let item in arr[i]) {
            str += `${arr[i][item]},`;
        }
        str += '\n';
    }
    //encodeURIComponent解決中文亂碼
    let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
    //通過創(chuàng)建a標簽實現(xiàn)
    let link = document.createElement("a");
    link.href = uri;
    //對下載的文件命名
    link.download = "數(shù)據(jù)表.csv";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

//爬取當前頁
currentCrawl();
//導出數(shù)據(jù)
tableToExcel();
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容