1. 程式人生 > >用nodejs寫簡單爬蟲抓取https淘寶頁面

用nodejs寫簡單爬蟲抓取https淘寶頁面

2016-09-23

周海漢 2016.9.23

淘寶有很多反爬措施。其中https就是反爬措施之一。一般的支援http協議的爬取失效了。

nodejs 是採用google V8引擎寫成的javascript後臺框架。自從有了nodejs,前端的開發才插上了騰飛的翅膀。由於javascript 是前端所使用最普遍的指令碼,因此在用nodejs處理網頁抓取時是非常方便,省力和獨到的。

比如我們想抓取淘寶的連衣裙的列表頁。(https://s.taobao.com/list?spm=a217f.8051907.312041.2.FfgfAo&style=grid&seller_type=taobao&cps=yes&cat=51108009)

先實現將頁面抓下來。

/*
 * crawler.js
 * Copyright (C) 2016 zhh <[email protected]>
 * http://abloz.com
 * ablo_zhou#163.com
 * Distributed under terms of the MIT license.
 */
var https = require('https')
var fs = require('fs')
var url='https://s.taobao.com/list?spm=a217f.8051907.312041.2.FfgfAo&style=grid&seller_type=taobao&cps=yes&cat=51108009';

https.get(url, function(res) {
    var html='';
    res.on('data', function(data) {
        html += data;
    });
    res.on('end',function() {
        console.log(html);
        fs.writeFile('taobao.html',html)
    });
}).on('error', function() {
    console.log('error');
});

[email protected] % node crawler.js

   <div class="js-disabled">
        <div class="bg"></div>
        <a class="logo" href="//www.taobao.com"></a>

        <p class="text">啟用指令碼才能顯示當前頁面, <a class="link"
                                         href="//bangpai.taobao.com/group/thread/400769-7367089.htm#reply60023761"
                                         target="_blank">點選啟用</a></p>
        <img src="/noscript.img" style="width: 0px;height: 0px;"/>

        <p class="bottom">&copy; 2003-2016 Taobao.com 版權所有</p>
    </div>
</noscript>

<!-- hello hotfix -->

</body>
</html>
<!--<?php Yii::app()->wm->runWidget('debuginfo') ?>-->

結果發現淘寶的頁面還是php實現的,而且還用了Yii框架。

[email protected] % ls crawler.js taobao.html

taobao.html就是我們剛抓取的頁面。和終端列印的內容一樣。

[email protected] % tail taobao.html

        <p class="bottom">&copy; 2003-2016 Taobao.com 版權所有</p>
    </div>
</noscript>

<!-- hello hotfix -->

</body>
</html>
<!--<?php Yii::app()->wm->runWidget('debuginfo') ?>-->

所以https抓取成功。

如非註明轉載, 均為原創. 本站遵循知識共享CC協議,轉載請註明來源