NodeJS クローラー クロール Huxiu ニュース

1. 依存ライブラリをローカルにインストールする 必要なライブラリは次のとおりです: インストール方法については、Node.js のノートを参照してください。
const superagent = require('superagent');
const cheerio = require('cheerio');
const async = require('async');
const fs = require('fs');
const url = require('url');
const request = require('request');

2. ホームページをクロールします。
 

const huxiuUrl = 'https://www.huxiu.com/';


function Huxiu_hot3(url){
this.url = url;
this.getindex = function(){
superagent.get(this.url).end(function(err, res) {
    if (err) {
     return console.error(err);
    }
    //cheerio nodejs版的JQ
    let $ = cheerio.load(res.text);
    //获取首页所有的链接
    //console.log(res.text);
   });
 }

}



var test = new Huxiu_hot3(huxiuUrl);
test.getindex();

(1) スーパーエージェントの概要は次のとおりです。
         Superagent は、nodeJS の非常に便利なクライアント リクエスト コード モジュールです。
         リクエスト方法には次のものがあります。
         取得(デフォルト)
         役職
         置く
         消去
         頭
(2) 文法:
request(RequestType, RequestUrl).end(callback(err, res));

(3) 書き方:
var request = require('superagent') 
request        //request表示superagent对象
   .post('/api/pet') 
   .send({ name: 'Manny', species: 'cat' }) 
   .set('X-API-Key', 'foobar') 
   .set('Accept', 'application/json') 
   .then(res => { alert('yay got ' + JSON.stringify(res.body)); 

});

3. ページデータ分析: cherio のload メソッドを通じてドキュメント全体を解析します。これは HTML ページのすべてのコンテンツであり、console.log($.html()); を通じてコン​​ソールで表示できます。あ>
(1) JQuery 構文を使用して DOM を操作します。 cheerio は、jquery の Node.js バージョンとして理解できるノード ライブラリです。CSS セレクターを使用して Web ページからデータを取得するために使用されます。使用方法は基本的に jquery と同じです。
$('div.big-pic-box div>a:first-child').each(function(idx,element){
    let $element = $(element);
    //console.log($element.attr('href'));
});

(2) JQuery トラバーサル関数: each() メソッドは、一致する要素ごとに実行される関数を指定します。
语法:$(selector).each(function(index,element))

* index - 选择器的 index 位置
* element - 当前的元素(也可使用 "this" 选择器)

(3) url.resolve メソッドの使用手順:   URL または href の元のタグを挿入または置換します。 次の目的で使用されます。必要な URL をすべて結合します
//由于该方法属于url模块,使用前需要引入url模块(var url= require(“url”) )
var url = require('url');
var a = url.resolve('/one/two/three', 'four') ,
b = url.resolve('http://example.com/', '/one'),
c = url.resolve('http://example.com/one', '/two');
console.log(a +","+ b +","+ c);
//输出结果:
///one/two/four
//http://example.com/one
//http://example.com/two

(4) ページによって解析されたターゲット URL を取得します。
$('div.big-pic-box div>a:first-child').each(function(idx,element){
    let $element = $(element);
    //console.log($element.attr('href'));
    let href = url.resolve(huxiuUrl, $element.attr('href'));
    // allUrl.push(href);
    console.log(href);
});

4. &#x (Unicode エンコードされた漢字) JS 変換方法:
let content = $('.article-wrap div.article-content-wrap').html(); //返回的是unicode编码的数据,需要 unicode 转中文
content = unescape(content.replace(/&#x/g,'%u').replace(/;/g,''))
console.log(content);

5. Json と文字列間の変換:
(1) json.stringfy() は、js オブジェクト (Object) と配列を文字列に変換します。
(2) json.parse() は、たとえば文字列 {} を json オブジェクトに変換しますが、JSON 形式に変換された場合にのみ、ret.id を使用して id の値を取得できます。
"{"token":"EAAehsk05sX4BAAoUt2w6Ecf1MxLY17V6DT3S9Wb9n4Ml7dGQ07lczhZAAUEXLXNXP87avp0LNfCc5eTilBguJOTAD1E8rtakT5pKJNxCiZAFsWPqw3yu2WiaWxHBRtbeBpreZCWpP2gqUnvv2O06MX3Wn7rHdlkcw0dfPCS0WjAfkX16Qe08nJOLHNfdIhcXnfkybeO5LIltFYdCQUh46JY96ZAogmkJiO0H4xB25QZDZD","id":"111374853316990","name":"Chunyu Tian","picture":"https://graph.facebook.com/v3.2/111374853316990/picture?height=64&width=64&migration_overrides=%7Boctober_2012%3Atrue%7D"}"

6.JS はフォルダー内のすべてのファイル名を読み取ります。
let  fs = require('fs');
let  join = require('path').join;
/**
*
* @param startPath  起始目录文件夹路径
* @returns {Array}
*/
function findSync(startPath) {
    let result=[];
    function finder(path) {
        let files=fs.readdirSync(path);
        files.forEach((val,index) => {
            let fPath=join(path,val);
            let stats=fs.statSync(fPath);
            if(stats.isDirectory()) finder(fPath);
            if(stats.isFile()) result.push(fPath);
        });

    }
    finder(startPath);
    return result;
}
let fileNames=findSync('./');

おすすめ

転載: blog.csdn.net/woshiyuyanjia/article/details/134831252