• 【nodejs】理想论坛帖子下载爬虫1.07 使用request模块后稳定多了


    在1.06版本时,访问网页采用的时http.request,但调用次数多以后就问题来了。

    寻找别的方案时看到了https://cnodejs.org/topic/53142ef833dbcb076d007230,感觉request可以试试,之前在别的地方也听人夸过。

    于是替换了saveTopicDetails函数的访问模块,经测试还不错,一万多条数据能跑下来,出错的几率不算高,不过今天也有休盘理想论坛压力轻的利好因素。

    代码如下:

    //======================================================
    // 理想论坛帖子下载爬虫1.07
    // saveTopicDetails中,使用request模块替代原来的http.request,稳定性大有提高
    // 2018年4月28日
    //======================================================
    var http=require("http");            // http模块
    var zlib = require('zlib');            // 用于解析gzip网页
    var fs=require('fs');                // 文件处理模块
    var iconv = require('iconv-lite');    // 用于转码。
    var cheerio = require("cheerio");    // 用于从HTML中以类似jquery方式查找目标
    var async=require('async');            // 用于异步流程控制
    var EventProxy = require('eventproxy');// 用来控制并发
    var BufferHelper = require('bufferhelper');// 用于拼接chunk
    
    //--- 下面为全局变量 ---
    var folder;// 存文件的目录
    var topics=[]; // 帖子数组
    var finalTopics=[];// 所有帖子加子贴的最终数组
    
    //-------------------------------
    // 用于创建目录
    //-------------------------------
    function createFolder(){
        console.log('准备创建目录');
    
        folder='infos('+currDateTime()+")";
        fs.mkdir('./'+folder,function(err){
            if(err){
                console.log("目录"+folder+"创建失败,因为"+err);
            }else{
                console.log("目录"+folder+"已创建");
            }
        });
    }
    
    //-------------------------------
    // 浏览页面找主贴
    // start:开始页,end:结束页
    //-------------------------------
    function findTopics(start,end){
        console.log('准备从以下页面寻找主贴');
    
        for(var i=start;i<=end;i++){        
            pageUrl='http://www.55188.com/forum-8-'+i+'.html'
            findTopicsInPage(pageUrl);
        }
    }
    
    //-------------------------------
    // 找到每个论坛页中的帖子
    // pageUrl:论坛页的地址
    //-------------------------------
    function findTopicsInPage(pageUrl){
        console.log("page="+pageUrl);
    
        var currUrl=pageUrl.replace("http://","");
        var pos=currUrl.indexOf("/");
        var hostname=currUrl.slice(0,pos);    
        var path=currUrl.slice(pos);    
        pos=currUrl.lastIndexOf("/");
        var dir="http://"+currUrl.slice(0,pos);            
        
        var options={
            hostname:hostname,
                port:80,
                path:path,
              method:'GET',        
        };    
    
        var req=http.request(options,function(resp){
            var html = [];
    
            resp.on("data", function(data) {
                html.push(data);
            })
            resp.on("end", function() {
                var buffer = Buffer.concat(html);
    
                var body = iconv.decode(buffer,'gb2312');
                var $ = cheerio.load(body);            
    
                $("tbody").each(function(index,element){
                    var $tbody=cheerio.load($(element).html());
    
                    var topic={};
                    topic.pageCount=1;
                    topic.url=null;
                    topic.title=null;
    
                    $tbody(".forumdisplay a").each(function(index,element){                
                        var topicUrl='http://www.55188.com/'+$tbody(element).attr("href");
                        var topicTitle=$tbody(element).text();
    
                        topic.url=topicUrl
                        topic.title=topicTitle;                        
                    })
    
                    $tbody(".threadpages").each(function(index,element){
                        topic.pageCount=$tbody(element).children().last().text();
                    })
                    
                    if(topic.url!=null && topic.title!=null){
                        topics.push(topic);    
                    }
                })  
            }).on("error", function(err) {
                console.log("findTopicsInPage函数请求后获取响应时出现异常"+err);
            })
        });
    
        // 超时处理
        req.setTimeout(7500,function(){
            req.abort();
        });
    
        // 出错处理
        req.on('error',function(err){
            console.log('findTopicsInPage函数请求时发生错误'+err);  
        });
    
        // 请求结束
        req.end();    
    }
    
    //-------------------------------
    // 保存每个帖子到文件,完成一个递归调自己一次
    // Nodejs特殊的回调处理使循环递归化
    //-------------------------------
    function saveTopicDetails(){
        if(finalTopics.length>0){
            var topic=finalTopics.pop();
            var topicUrl=topic.url;
            var topicTitle=topic.title;
            var index=topic.index;
    
            var request = require('request');
            var req = request(topic.url, {timeout: 10000, pool: false});
            req.setMaxListeners(50);
            req.setHeader('user-agent', 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36');
    
            req.on('error', function(err) {
                var text=nowTime()+"saveTopicDetail函数请求时出现异常"+err+'
    ';
                text+=nowTime()+" url="+topicUrl+'
    ';
                text+=nowTime()+" title="+topicTitle+'
    ';
                text+=nowTime()+" index="+index+'
    ';
                console.log(coloredText(text,'red'));
                ///
                saveTopicDetails();//出错后依旧递归
            });
            req.on('response', function(res) {
                var bufferHelper = new BufferHelper();
                res.on('data', function (chunk) {
                    bufferHelper.concat(chunk);
                });
                res.on('end',function(){
                    var body = iconv.decode(bufferHelper.toBuffer(),'GBK');
                    //console.log(body);
    
                    var $ = cheerio.load(body);
                    var infos=[];// 获得的发帖人信息
    
                    // 得到发帖人信息
                    $(".postinfo").each(function(index,element){                    
                        var content=$(element).text();
                        content=content.replace(/s+/g,' ');// 空白字符替换为一个空格
                        var arr=content.split(" ");// 以空格劈分
                        
                        if(arr.length==7){
                            info={'url':topicUrl,
                                  'title':topicTitle,
                                  '楼层':arr[1],
                                  '作者':arr[2].replace('只看:',''),
                                  '日期':arr[4],
                                  '时间':arr[5]};
                            infos.push(info);
                            //console.log('info='+info);
                        }else if(arr.length==8){
                            info={'url':topicUrl,
                                  'title':topicTitle,
                                  '楼层':arr[1],
                                  '作者':arr[2].replace('只看:',''),
                                  '日期':arr[5],
                                  '时间':arr[6]};
                            infos.push(info);
                            //console.log('info='+info);
                        }
                    })
    
                    if(infos.length>0){
                        var text=JSON.stringify(infos);
    
                        filename='./'+folder+'/'+index+'.dat';
    
                        fs.writeFile(filename,text,function(err){
                            if(err){
                                console.log('写入文件'+filename+'失败,因为'+err);
                            }
                        });
    
                        if(index % 50==0){
                            console.log(coloredText(nowTime()+'第'+index+'个文件保存完毕','green'));//让控制台出点动静
                        }
    
                        saveTopicDetails();//一个帖子完成,递归一次
                    }
                });
            })
        }
    }
    
    //-------------------------------
    // 入口函数
    // start:起始页,从1开始
    // end:终止页,>start
    //-------------------------------
    function main(start,end){
    
        var flow=require('nimble');
    
        flow.series([
            function(callback){
                setTimeout(function(){ 
                    createFolder();
                    callback();
                },100);
            },
    
            function(callback){
                setTimeout(function(){ 
                    findTopics(start,end);
                    callback();
                },100);
            },
    
            function(callback){
                setTimeout(function(){ 
                    var n=topics.length;
                    console.log("共找到"+n+"个帖子");
    
                    // 获得每个子贴所在地址,序号和标题
                    var index=0;
                    var arr=[];
                    for(var i=0;i<n;i++){
                        var topic=topics[i];
    
                        for(var j=1;j<=topic.pageCount;j++){
                            var regexp=new RegExp(/-(d+)-(d+)-(d+)/);
                            var topicUrl=topic.url.replace(regexp,"-$1-"+j+"-$3");// 用正则表达式替换第二个数字
                            
                            index++;
                    
                            var item={'index':index,'url':topicUrl,'title':topic.title};
                            arr.push(item);
                        }
                    }                
                    
                    finalTopics=arr;// 所有帖子加子贴的最终数组
                    finalTopics.reverse();
                    console.log('拟生成文件'+finalTopics.length+'个');
    
                    saveTopicDetails();
    
                    callback();
                },3000);
            },
        ]);
    }
    
    //--------------------------------------
    // 通用函数,返回当前日期时间 创建目录用
    //--------------------------------------
    function currDateTime() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = "_";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate =date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds();
        return currentdate;
    }
    
    //--------------------------------------
    // 通用函数,返回当前日期时间 控制台输出时间用
    //--------------------------------------
    function nowTime() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate =date.getFullYear() + seperator1 + month + seperator1 + strDate
                + " " + date.getHours() + seperator2 + date.getMinutes()
                + seperator2 + date.getSeconds()+ " ";
        return currentdate;
    }
    
    //-------------------------------
    // 得到带颜色(前景色)的文字,用于在控制台输出
    // text:文字,color:前景色
    //-------------------------------
    function coloredText(text,color){
        var dic = new Array();
    
        dic["white"] = ['x1B[37m', 'x1B[39m'];
        dic["grey"] = ['x1B[90m', 'x1B[39m'];
        dic["black"] = ['x1B[30m', 'x1B[39m'];
        dic["blue"] = ['x1B[34m', 'x1B[39m'];
        dic["cyan"] = ['x1B[36m', 'x1B[39m'];
        dic["green"] = ['x1B[32m', 'x1B[39m'];
        dic["magenta"] = ['x1B[35m', 'x1B[39m'];
        dic["red"] = ['x1B[31m', 'x1B[39m'];
        dic["yellow"] = ['x1B[33m', 'x1B[39m'];
    
        return dic[color][0]+text+dic[color][1];
    }
    
    // 开始
    main(1,2);

    控制台的输出:

    C:Usershorn1Desktop
    ode.js62-理想论坛爬虫1.07>node lixiang.js
    准备创建目录
    目录infos(2018-04-28 9_24_35)已创建
    准备从以下页面寻找主贴
    page=http://www.55188.com/forum-8-1.html
    page=http://www.55188.com/forum-8-2.html
    共找到140个帖子
    拟生成文件11295个
    2018-04-28 9:25:28 第50个文件保存完毕
    2018-04-28 9:26:12 第100个文件保存完毕
    2018-04-28 9:26:54 第150个文件保存完毕
    2018-04-28 9:27:46 第200个文件保存完毕
    2018-04-28 9:28:39 第250个文件保存完毕
    2018-04-28 9:28:54 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: ETIMEDOUT
    2018-04-28 9:28:54  url=http://www.55188.com/thread-3980834-256-2.html
    2018-04-28 9:28:54  title= 晓哥的投资生涯:超长线实盘贴
    2018-04-28 9:28:54  index=256
    
    2018-04-28 9:28:55 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: getaddrinfo ENOTFOUND www.55188.com www.55188.com:80
    2018-04-28 9:28:55  url=http://www.55188.com/thread-3980834-257-2.html
    2018-04-28 9:28:55  title= 晓哥的投资生涯:超长线实盘贴
    2018-04-28 9:28:55  index=257
    
    2018-04-28 9:29:40 第300个文件保存完毕
    2018-04-28 9:30:40 第350个文件保存完毕
    2018-04-28 9:31:37 第400个文件保存完毕
    2018-04-28 9:32:47 第450个文件保存完毕
    2018-04-28 9:33:44 第500个文件保存完毕
    2018-04-28 9:34:55 第550个文件保存完毕
    2018-04-28 9:35:54 第600个文件保存完毕
    2018-04-28 9:36:47 第650个文件保存完毕
    2018-04-28 9:37:39 第700个文件保存完毕
    2018-04-28 9:38:32 第750个文件保存完毕
    2018-04-28 9:39:25 第800个文件保存完毕
    2018-04-28 9:40:23 第850个文件保存完毕
    2018-04-28 9:41:24 第900个文件保存完毕
    2018-04-28 9:42:22 第950个文件保存完毕
    2018-04-28 9:43:23 第1000个文件保存完毕
    2018-04-28 9:44:22 第1050个文件保存完毕
    2018-04-28 9:45:16 第1100个文件保存完毕
    2018-04-28 9:46:13 第1150个文件保存完毕
    2018-04-28 9:47:13 第1200个文件保存完毕
    2018-04-28 9:48:6 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: ETIMEDOUT
    2018-04-28 9:48:6  url=http://www.55188.com/thread-8158615-241-2.html
    2018-04-28 9:48:6  title= 未来牛市会以什么方式运行?
    2018-04-28 9:48:6  index=1242
    
    2018-04-28 9:48:7 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: getaddrinfo ENOTFOUND www.55188.com www.55188.com:80
    2018-04-28 9:48:7  url=http://www.55188.com/thread-8158615-242-2.html
    2018-04-28 9:48:7  title= 未来牛市会以什么方式运行?
    2018-04-28 9:48:7  index=1243
    
    2018-04-28 9:48:13 第1250个文件保存完毕
    2018-04-28 9:49:6 第1300个文件保存完毕
    2018-04-28 9:49:56 第1350个文件保存完毕
    2018-04-28 9:50:46 第1400个文件保存完毕
    2018-04-28 9:51:34 第1450个文件保存完毕
    2018-04-28 9:52:19 第1500个文件保存完毕
    2018-04-28 9:53:6 第1550个文件保存完毕
    2018-04-28 9:53:50 第1600个文件保存完毕
    2018-04-28 9:54:36 第1650个文件保存完毕
    2018-04-28 9:55:33 第1700个文件保存完毕
    2018-04-28 9:56:40 第1750个文件保存完毕
    2018-04-28 9:57:48 第1800个文件保存完毕
    2018-04-28 9:58:48 第1850个文件保存完毕
    2018-04-28 9:59:49 第1900个文件保存完毕
    2018-04-28 10:0:38 第1950个文件保存完毕
    2018-04-28 10:1:24 第2000个文件保存完毕
    2018-04-28 10:2:12 第2050个文件保存完毕
    2018-04-28 10:2:26 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: ETIMEDOUT
    2018-04-28 10:2:26  url=http://www.55188.com/thread-7507861-278-2.html
    2018-04-28 10:2:26  title= 主力的心思你别猜——一个老手的经验分享
    2018-04-28 10:2:26  index=2055
    
    2018-04-28 10:2:27 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: getaddrinfo ENOTFOUND www.55188.com www.55188.com:80
    2018-04-28 10:2:27  url=http://www.55188.com/thread-7507861-279-2.html
    2018-04-28 10:2:27  title= 主力的心思你别猜——一个老手的经验分享
    2018-04-28 10:2:27  index=2056
    
    2018-04-28 10:3:11 第2100个文件保存完毕
    2018-04-28 10:3:59 第2150个文件保存完毕
    2018-04-28 10:4:41 第2200个文件保存完毕
    2018-04-28 10:5:27 第2250个文件保存完毕
    2018-04-28 10:6:16 第2300个文件保存完毕
    2018-04-28 10:7:8 第2350个文件保存完毕
    2018-04-28 10:8:5 第2400个文件保存完毕
    2018-04-28 10:9:6 第2450个文件保存完毕
    2018-04-28 10:9:58 第2500个文件保存完毕
    2018-04-28 10:10:51 第2550个文件保存完毕
    2018-04-28 10:11:43 第2600个文件保存完毕
    2018-04-28 10:12:40 第2650个文件保存完毕
    2018-04-28 10:13:32 第2700个文件保存完毕
    2018-04-28 10:14:24 第2750个文件保存完毕
    2018-04-28 10:15:21 第2800个文件保存完毕
    2018-04-28 10:16:10 第2850个文件保存完毕
    2018-04-28 10:17:6 第2900个文件保存完毕
    2018-04-28 10:17:52 第2950个文件保存完毕
    2018-04-28 10:18:45 第3000个文件保存完毕
    2018-04-28 10:19:40 第3050个文件保存完毕
    2018-04-28 10:20:31 第3100个文件保存完毕
    2018-04-28 10:21:26 第3150个文件保存完毕
    2018-04-28 10:22:13 第3200个文件保存完毕
    2018-04-28 10:23:4 第3250个文件保存完毕
    2018-04-28 10:23:53 第3300个文件保存完毕
    2018-04-28 10:24:48 第3350个文件保存完毕
    2018-04-28 10:25:56 第3400个文件保存完毕
    2018-04-28 10:26:50 第3450个文件保存完毕
    2018-04-28 10:27:47 第3500个文件保存完毕
    2018-04-28 10:28:42 第3550个文件保存完毕
    2018-04-28 10:29:54 第3600个文件保存完毕
    2018-04-28 10:30:46 第3650个文件保存完毕
    2018-04-28 10:31:42 第3700个文件保存完毕
    2018-04-28 10:32:34 第3750个文件保存完毕
    2018-04-28 10:33:21 第3800个文件保存完毕
    2018-04-28 10:34:11 第3850个文件保存完毕
    2018-04-28 10:34:59 第3900个文件保存完毕
    2018-04-28 10:35:51 第3950个文件保存完毕
    2018-04-28 10:36:45 第4000个文件保存完毕
    2018-04-28 10:37:37 第4050个文件保存完毕
    2018-04-28 10:38:37 第4100个文件保存完毕
    2018-04-28 10:39:34 第4150个文件保存完毕
    2018-04-28 10:40:41 第4200个文件保存完毕
    2018-04-28 10:41:38 第4250个文件保存完毕
    2018-04-28 10:42:45 第4300个文件保存完毕
    2018-04-28 10:43:38 第4350个文件保存完毕
    2018-04-28 10:44:38 第4400个文件保存完毕
    2018-04-28 10:45:37 第4450个文件保存完毕
    2018-04-28 10:46:35 第4500个文件保存完毕
    2018-04-28 10:47:18 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: ETIMEDOUT
    2018-04-28 10:47:18  url=http://www.55188.com/thread-8107404-72-2.html
    2018-04-28 10:47:18  title= 操盘秘籍--抓涨停公式与方法+短线买卖选股/附图公式【通达信版】
    2018-04-28 10:47:18  index=4529
    
    2018-04-28 10:47:19 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: getaddrinfo ENOTFOUND www.55188.com www.55188.com:80
    2018-04-28 10:47:19  url=http://www.55188.com/thread-8107404-73-2.html
    2018-04-28 10:47:19  title= 操盘秘籍--抓涨停公式与方法+短线买卖选股/附图公式【通达信版】
    2018-04-28 10:47:19  index=4530
    
    2018-04-28 10:47:39 第4550个文件保存完毕
    2018-04-28 10:48:29 第4600个文件保存完毕
    2018-04-28 10:49:25 第4650个文件保存完毕
    2018-04-28 10:50:13 第4700个文件保存完毕
    2018-04-28 10:51:1 第4750个文件保存完毕
    2018-04-28 10:51:59 第4800个文件保存完毕
    2018-04-28 10:52:52 第4850个文件保存完毕
    2018-04-28 10:53:37 第4900个文件保存完毕
    2018-04-28 10:54:32 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: ETIMEDOUT
    2018-04-28 10:54:32  url=http://www.55188.com/thread-7868629-31-2.html
    2018-04-28 10:54:32  title= 在实战中学习
    2018-04-28 10:54:32  index=4939
    
    2018-04-28 10:54:33 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: getaddrinfo ENOTFOUND www.55188.com www.55188.com:80
    2018-04-28 10:54:33  url=http://www.55188.com/thread-7868629-32-2.html
    2018-04-28 10:54:33  title= 在实战中学习
    2018-04-28 10:54:33  index=4940
    
    2018-04-28 10:54:49 第4950个文件保存完毕
    2018-04-28 10:55:48 第5000个文件保存完毕
    2018-04-28 10:56:46 第5050个文件保存完毕
    2018-04-28 10:57:50 第5100个文件保存完毕
    2018-04-28 10:59:7 第5150个文件保存完毕
    2018-04-28 11:0:29 第5200个文件保存完毕
    2018-04-28 11:2:2 第5250个文件保存完毕
    2018-04-28 11:3:29 第5300个文件保存完毕
    2018-04-28 11:5:26 第5350个文件保存完毕
    2018-04-28 11:6:27 第5400个文件保存完毕
    2018-04-28 11:7:30 第5450个文件保存完毕
    2018-04-28 11:8:31 第5500个文件保存完毕
    2018-04-28 11:9:36 第5550个文件保存完毕
    2018-04-28 11:10:36 第5600个文件保存完毕
    2018-04-28 11:11:28 第5650个文件保存完毕
    2018-04-28 11:12:25 第5700个文件保存完毕
    2018-04-28 11:13:16 第5750个文件保存完毕
    2018-04-28 11:14:12 第5800个文件保存完毕
    2018-04-28 11:15:18 第5850个文件保存完毕
    2018-04-28 11:18:9 第5900个文件保存完毕
    2018-04-28 11:19:11 第5950个文件保存完毕
    2018-04-28 11:20:26 第6000个文件保存完毕
    2018-04-28 11:21:43 第6050个文件保存完毕
    2018-04-28 11:23:10 第6100个文件保存完毕
    2018-04-28 11:24:14 第6150个文件保存完毕
    2018-04-28 11:25:14 第6200个文件保存完毕
    2018-04-28 11:26:16 第6250个文件保存完毕
    2018-04-28 11:27:21 第6300个文件保存完毕
    2018-04-28 11:28:19 第6350个文件保存完毕
    2018-04-28 11:29:28 第6400个文件保存完毕
    2018-04-28 11:30:34 第6450个文件保存完毕
    2018-04-28 11:31:30 第6500个文件保存完毕
    2018-04-28 11:32:33 第6550个文件保存完毕
    2018-04-28 11:33:32 第6600个文件保存完毕
    2018-04-28 11:34:35 第6650个文件保存完毕
    2018-04-28 11:35:27 第6700个文件保存完毕
    2018-04-28 11:36:22 第6750个文件保存完毕
    2018-04-28 11:37:19 第6800个文件保存完毕
    2018-04-28 11:38:21 第6850个文件保存完毕
    2018-04-28 11:39:27 第6900个文件保存完毕
    2018-04-28 11:40:34 第6950个文件保存完毕
    2018-04-28 11:41:33 第7000个文件保存完毕
    2018-04-28 11:42:34 第7050个文件保存完毕
    2018-04-28 11:43:26 第7100个文件保存完毕
    2018-04-28 11:44:22 第7150个文件保存完毕
    2018-04-28 11:45:22 第7200个文件保存完毕
    2018-04-28 11:46:23 第7250个文件保存完毕
    2018-04-28 11:47:25 第7300个文件保存完毕
    2018-04-28 11:48:33 第7350个文件保存完毕
    2018-04-28 11:49:30 第7400个文件保存完毕
    2018-04-28 11:50:29 第7450个文件保存完毕
    2018-04-28 11:51:33 第7500个文件保存完毕
    2018-04-28 11:52:45 第7550个文件保存完毕
    2018-04-28 11:53:52 第7600个文件保存完毕
    2018-04-28 11:54:57 第7650个文件保存完毕
    2018-04-28 11:56:2 第7700个文件保存完毕
    2018-04-28 11:57:19 第7750个文件保存完毕
    2018-04-28 11:58:20 第7800个文件保存完毕
    2018-04-28 11:59:13 第7850个文件保存完毕
    2018-04-28 12:0:3 第7900个文件保存完毕
    2018-04-28 12:0:54 第7950个文件保存完毕
    2018-04-28 12:2:1 第8000个文件保存完毕
    2018-04-28 12:2:48 第8050个文件保存完毕
    2018-04-28 12:3:40 第8100个文件保存完毕
    2018-04-28 12:4:30 第8150个文件保存完毕
    2018-04-28 12:5:38 第8200个文件保存完毕
    2018-04-28 12:6:40 第8250个文件保存完毕
    2018-04-28 12:8:3 第8300个文件保存完毕
    2018-04-28 12:9:1 第8350个文件保存完毕
    2018-04-28 12:9:56 第8400个文件保存完毕
    2018-04-28 12:10:44 第8450个文件保存完毕
    2018-04-28 12:11:44 第8500个文件保存完毕
    2018-04-28 12:12:38 第8550个文件保存完毕
    2018-04-28 12:13:28 第8600个文件保存完毕
    2018-04-28 12:14:33 第8650个文件保存完毕
    2018-04-28 12:15:27 第8700个文件保存完毕
    2018-04-28 12:16:24 第8750个文件保存完毕
    2018-04-28 12:17:17 第8800个文件保存完毕
    2018-04-28 12:18:6 第8850个文件保存完毕
    2018-04-28 12:19:1 第8900个文件保存完毕
    2018-04-28 12:20:3 第8950个文件保存完毕
    2018-04-28 12:21:4 第9000个文件保存完毕
    2018-04-28 12:21:57 第9050个文件保存完毕
    2018-04-28 12:22:53 第9100个文件保存完毕
    2018-04-28 12:23:45 第9150个文件保存完毕
    2018-04-28 12:24:37 第9200个文件保存完毕
    2018-04-28 12:25:37 第9250个文件保存完毕
    2018-04-28 12:26:29 第9300个文件保存完毕
    2018-04-28 12:27:22 第9350个文件保存完毕
    2018-04-28 12:28:30 第9400个文件保存完毕
    2018-04-28 12:29:28 第9450个文件保存完毕
    2018-04-28 12:30:15 第9500个文件保存完毕
    2018-04-28 12:31:12 第9550个文件保存完毕
    2018-04-28 12:32:14 第9600个文件保存完毕
    2018-04-28 12:33:9 第9650个文件保存完毕
    2018-04-28 12:33:57 第9700个文件保存完毕
    2018-04-28 12:34:59 第9750个文件保存完毕
    2018-04-28 12:36:2 第9800个文件保存完毕
    2018-04-28 12:36:56 第9850个文件保存完毕
    2018-04-28 12:38:1 第9900个文件保存完毕
    2018-04-28 12:39:1 第9950个文件保存完毕
    2018-04-28 12:39:58 第10000个文件保存完毕
    2018-04-28 12:40:56 第10050个文件保存完毕
    2018-04-28 12:41:51 第10100个文件保存完毕
    2018-04-28 12:44:45 第10150个文件保存完毕
    2018-04-28 12:45:41 第10200个文件保存完毕
    2018-04-28 12:46:38 第10250个文件保存完毕
    2018-04-28 12:47:40 第10300个文件保存完毕
    2018-04-28 12:48:33 第10350个文件保存完毕
    2018-04-28 12:49:36 第10400个文件保存完毕
    2018-04-28 12:50:24 第10450个文件保存完毕
    2018-04-28 12:51:24 第10500个文件保存完毕
    2018-04-28 12:52:19 第10550个文件保存完毕
    2018-04-28 12:53:12 第10600个文件保存完毕
    2018-04-28 12:54:8 第10650个文件保存完毕
    2018-04-28 12:54:59 第10700个文件保存完毕
    2018-04-28 12:55:44 第10750个文件保存完毕
    2018-04-28 12:56:36 第10800个文件保存完毕
    2018-04-28 12:57:36 第10850个文件保存完毕
    2018-04-28 12:58:38 第10900个文件保存完毕
    2018-04-28 12:59:48 第10950个文件保存完毕
    2018-04-28 13:0:50 第11000个文件保存完毕
    2018-04-28 13:1:52 第11050个文件保存完毕
    2018-04-28 13:2:51 第11100个文件保存完毕
    2018-04-28 13:3:30 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: ETIMEDOUT
    2018-04-28 13:3:30  url=http://www.55188.com/thread-8229004-289-1.html
    2018-04-28 13:3:30  title= 淡定小生2018实盘交流贴
    2018-04-28 13:3:30  index=11125
    
    2018-04-28 13:4:19 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: ESOCKETTIMEDOUT
    2018-04-28 13:4:19  url=http://www.55188.com/thread-8229004-312-1.html
    2018-04-28 13:4:19  title= 淡定小生2018实盘交流贴
    2018-04-28 13:4:19  index=11148
    
    2018-04-28 13:4:23 第11150个文件保存完毕
    2018-04-28 13:4:40 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: ESOCKETTIMEDOUT
    2018-04-28 13:4:40  url=http://www.55188.com/thread-8229004-328-1.html
    2018-04-28 13:4:40  title= 淡定小生2018实盘交流贴
    2018-04-28 13:4:40  index=11164
    
    2018-04-28 13:4:40 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: ESOCKETTIMEDOUT
    2018-04-28 13:4:40  url=http://www.55188.com/thread-8229004-327-1.html
    2018-04-28 13:4:40  title= 淡定小生2018实盘交流贴
    2018-04-28 13:4:40  index=11163
    
    2018-04-28 13:5:5 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: ESOCKETTIMEDOUT
    2018-04-28 13:5:5  url=http://www.55188.com/thread-8320599-1-1.html
    2018-04-28 13:5:5  title= 蔡康侨说A股~~~(2018 Q2) 节后变盘向上、变数在6月
    2018-04-28 13:5:5  index=11190
    
    2018-04-28 13:5:17 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: ESOCKETTIMEDOUT
    2018-04-28 13:5:17  url=http://www.55188.com/thread-8320599-5-1.html
    2018-04-28 13:5:17  title= 蔡康侨说A股~~~(2018 Q2) 节后变盘向上、变数在6月
    2018-04-28 13:5:17  index=11194
    
    2018-04-28 13:5:19 第11200个文件保存完毕
    2018-04-28 13:5:36 第11250个文件保存完毕
    2018-04-28 13:5:53 saveTopicDetail函数请求后(on_error)获取响应时出现异常Error: ESOCKETTIMEDOUT
    2018-04-28 13:5:53  url=http://www.55188.com/thread-7938789-9-1.html
    2018-04-28 13:5:53  title= 结构分析法
    2018-04-28 13:5:53  index=11257
    
    
    C:Usershorn1Desktop
    ode.js62-理想论坛爬虫1.07>python insertDB.py

      将向数据库插入224452条记录
      已向数据库插入224452条记录
      插数据用时83秒

     

    插数据库的代码:

    # 读取理想论坛爬虫生成的数据,然后写入DB
    import pymysql
    import time
    import datetime
    import os
    import json
    
    # 数据库插值
    def insertDB(sqls):
        conn=pymysql.connect(host='127.0.0.1',user='root',passwd='12345678',db='test',charset='utf8')
        
        sum=0;# 插入成功总数
    
        
        for sql in sqls:        
            try:
                count=conn.query(sql)    #单条是否成功    
            except Exception as e:
                print("sql'"+sql+"'出现异常:"+str(e))
                continue;
    
            if count==0:
                print(sql+'插入记录失败');    
                
            sum+=count
        
        conn.commit()
        conn.close()
    
        return sum
    
    # 入口函数
    def main(folder):
        starttime = datetime.datetime.now()
    
        allinfos=[]
        for filename in os.listdir(folder):
            filePathname=folder+"/"+filename
    
            with open(filePathname,'r',encoding='utf-8') as fObj:
                infos=json.load(fObj)
                #print(infos)
                allinfos.extend(infos)
    
        sqls=[]
        for info in allinfos:
            sql="insert into test.topic16(floor,author,tdate,ttime,addtime,url,title) values ('"
            sql=sql+info['楼层']+"','"
            sql=sql+info['作者'].replace("'","")+"','"
            sql=sql+info['日期']+"','"
            sql=sql+info['时间']+"',"
            sql=sql+"now(),'"
            sql=sql+info['url']+"','"
            sql=sql+info['title'].replace("'","")+"' "
            sql=sql+" )"
    
            sqls.append(sql)
    
        print("将向数据库插入"+str(len(sqls))+"条记录")
        retval=insertDB(sqls)
        print("已向数据库插入"+str(retval)+"条记录")
    
        endtime = datetime.datetime.now()
        print("插数据用时"+str((endtime - starttime).seconds)+"")
    # 开始
    main("./infos(2018-04-28 9_24_35)")

    数据库的情况:

  • 相关阅读:
    Python一些常用模块
    八、线程和进程
    七、Selenium与phantomJS----------动态页面模拟点击、网站模拟登录
    一、scrapy的下载安装---Windows(安装软件太让我伤心了)
    六、BeautifulSoup4------自动登录网站(手动版)
    五、XML与xpath--------------爬取美女图片
    四、正则表达式re模块
    三、Requests库的使用
    二、urllib进阶
    一、爬虫的基本体系和urllib的基本使用
  • 原文地址:https://www.cnblogs.com/heyang78/p/8967048.html
Copyright © 2020-2023  润新知