继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

node批量下载读者文章

HerryLo
关注TA
已关注
手记 33
粉丝 845
获赞 196

代码地址
需要在目录下创建名为 dz 的目录

安装依赖

```
    安装 node  npm
    # npm install cheerio --sava-dev
    # npm install request --sava-dev
```
const request= require('request');
const fs = require('fs');
const path = require('path');
const cheerio = require('cheerio');

const time = '2017_11'
const baseurl = 'http://www.52duzhe.com/'+time+'/';
const firsturl = baseurl + 'index.html';

function requestHtml(url) {
    return new Promise((resolve, reject)=>{
        request(url, function(err, res, body){
            if(!err && res.statusCode == 200){
                resolve(body);
            }
        })
    })
}

function main() {
    requestHtml(firsturl).then((res)=> {
        const $ = cheerio.load(res);
        const list = $('.booklist a');
        list.each(function(a,item){
            const newurl = baseurl+ $(item).attr('href');
            requestHtml(newurl).then((data)=>{
                let content = '';
                const $ = cheerio.load(data);
                let title = $('h1').text();
                let writer = $('#pub_date').text();
                let filename = path.join(__dirname, '/dz/'+title+'.txt');
                content += `<<${title}>>\n\n`;
                content += `${writer}\n\n`;
                let text = $('.blkContainerSblkCon p');
                text.each(function(a, b){
                    content += $(b).text();
                })
                fs.writeFile(filename, content, function(err){
                    if(err){
                        console.log(err);
                    }else{
                        console.log(filename+'创建成功');
                    }
                })
            })
        })
    })
}

main();
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP