Node.js umei圖片批量下載Node.js爬蟲1.00

這個爬蟲在abaike爬蟲的基礎上改改圖片路徑和下一頁路徑就出來了,代碼如下:

//======================================================
// umei圖片批量下載Node.js爬蟲1.00
// 2017年11月13日
//======================================================// 內置http模塊
var http=require("http");// 內置文件處理模塊,用于創建目錄和圖片文件
var fs=require('fs');// cheerio模塊,提供了類似jQuery的功能,用于從HTML code中查找圖片地址和下一頁
var cheerio = require("cheerio");// 請求參數JSON。http和https都有使用
var options;// request請求
var req;// 圖片數組,找到的圖片地址會放到這里
var pictures=[];//--------------------------------------
// 爬取網頁,找圖片地址,再爬
// pageUrl sample:http://www.umei.cc/meinvtupian/waiguomeinv/12667.htm
// pageUrl sample:http://www.umei.cc/meinvtupian/waiguomeinv/12667_3.htm
//--------------------------------------
function crawl(pageUrl){console.log("Current page="+pageUrl);// 得到hostname和pathvar currUrl=pageUrl.replace("http://","");var pos=currUrl.indexOf("/");var hostname=currUrl.slice(0,pos);        var path=currUrl.slice(pos);    //console.log("hostname="+hostname);//console.log("path="+path);// 初始化options  options={hostname:hostname,port:80,path:path,// 子路徑method:'GET',};req=http.request(options,function(resp){resp.setEncoding('utf8');var body="";resp.on('data',function(chunk){body+=chunk;            });resp.on('end',function(){//console.log("body="+body);var $ = cheerio.load(body);        var picCount=0;// 找圖片放入數組$(".ImageBody p img").each(function(index,element){var picUrl=$(element).attr("src");//console.log(picUrl);if(picUrl.indexOf('.jpg')!=-1){pictures.push(picUrl); picCount++;} })   console.log("找到圖片"+picCount+"張.");var nextPageUrl=null;// 找下一頁$(".NewPages ul li a").each(function(index,element){var text=$(element).text();if(text.indexOf('下一頁')!=-1){nextPageUrl=$(element).attr("href");nextPageUrl="http://www.umei.cc/"+nextPageUrl;// 把省略部分加上console.log("找到下一頁.");}        })if(nextPageUrl==null){console.log(pageUrl+"已經是最后一頁了.");download(pictures);}else{//console.log("下一頁是"+nextPageUrl);
                crawl(nextPageUrl);}});});// 超時處理req.setTimeout(10000,function(){req.abort();});// 出錯處理req.on('error',function(err){if(err.code=="ECONNRESET"){console.log('[crawl]socket端口連接超時。');console.log(err);}else{console.log('請求發生錯誤,err.code:'+err.code);console.log(err);}});// 請求結束
    req.end();
}var total=0;
var succeed=0;
var failed=0;//--------------------------------------
// 下載圖片
//--------------------------------------
function download(pictures){var folder='pictures('+getNowFormatDate()+")";// 創建目錄fs.mkdir('./'+folder,function(err){if(err){console.log("目錄"+folder+"已經存在");}});total=pictures.length;console.log("總計有"+total+"張圖片將被下載.");appendToLogfile(folder,"總計有"+total+"張圖片將被下載.\n");for(var i=0;i<pictures.length;i++){var picUrl=pictures[i];downloadPic(picUrl,folder);}
}//--------------------------------------
// 寫log文件
//--------------------------------------
function appendToLogfile(folder,text){fs.appendFile('./'+folder+'/log.txt', text, function (err) {if(err){console.log("不能書寫log文件");console.log(err);}});
}//--------------------------------------
// 取得當前時間
//--------------------------------------
function getNowFormatDate() {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;
}//--------------------------------------
// 下載單張圖片
// picUrl sample:http://www.avbaike.net/wp-content/uploads/2016/08/108.jpg
//--------------------------------------
function downloadPic(picUrl,folder){console.log("圖片:"+picUrl+"下載開始");// 得到hostname和pathvar currUrl=picUrl.replace("http://","");var pos=currUrl.indexOf("/");var hostname=currUrl.slice(0,pos);        var path=currUrl.slice(pos);    //console.log("hostname="+hostname);//console.log("path="+path);var picName=currUrl.slice(currUrl.lastIndexOf("/"));// 初始化options  options={hostname:hostname,port:80,path:path,// 子路徑method:'GET',};req=http.request(options,function(resp){var imgData = "";resp.setEncoding("binary"); resp.on('data',function(chunk){imgData+=chunk;            });resp.on('end',function(){        // 創建文件var fileName="./"+folder+picName;fs.writeFile(fileName, imgData, "binary", function(err){if(err){console.log("[downloadPic]文件"+fileName+"下載失敗.");console.log(err);appendToLogfile(folder,"文件"+fileName+"下載失敗.\n");failed++;}else{console.log("文件"+fileName+"下載成功");succeed++;}});    });});// 超時處理req.setTimeout(7500,function(){req.abort();});// 出錯處理req.on('error',function(err){if(err){console.log('[downloadPic]文件'+picUrl+"下載失敗,"+'因為'+err);appendToLogfile(folder,"文件"+picUrl+"下載失敗.\n");}failed++;});// 請求結束
    req.end();
}//--------------------------------------
// 程序入口 
//--------------------------------------
function getInput(){process.stdout.write("\033[35m 請輸入第一頁URL:\033[039m");    //紫色
    process.stdin.resume();process.stdin.setEncoding('utf8');    process.stdin.on('data',function(text){process.stdin.end();// 退出輸入狀態        crawl(text.trim());// trim()是必須的!        
    });    
}// 調用getInput函數,程序開始
getInput();

2017年11月13日20:05:44

轉載于:https://www.cnblogs.com/xiandedanteng/p/7827890.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/390831.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/390831.shtml
英文地址,請注明出處:http://en.pswp.cn/news/390831.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

交通銀行信息技術管理部副總經理張漫麗:交通銀行“大數據+人工智能”應用研究...

文 | 交通銀行信息技術管理部副總經理張漫麗 大數據隱含著巨大的社會、經濟、科研價值&#xff0c;已引起了各行各業的高度重視。如果能通過人工智能技術有效地組織和使用大數據&#xff0c;將對社會經濟和科學研究發展產生巨大的推動作用&#xff0c;同時也孕育著前所未有的機…

安軟件一勞永逸_如何克服一勞永逸地公開演講的恐懼

安軟件一勞永逸If you’re like most people, the idea of public speaking terrifies you (it terrifies me too). So how do you get over those jitters, get up on stage, and give an amazing talk? First, a disclaimer: this article is purely about your stage prese…

Go語言實戰 : API服務器 (8) 中間件

為什么需要中間件 我們可能需要對每個請求/返回做一些特定的操作&#xff0c;比如 記錄請求的 log 信息在返回中插入一個 Header部分接口進行鑒權 這些都需要一個統一的入口。這個功能可以通過引入 middleware 中間件來解決。Go 的 net/http 設計的一大特點是特別容易構建中間…

缺失值和異常值的識別與處理_識別異常值-第一部分

缺失值和異常值的識別與處理&#x1f4c8;Python金融系列 (&#x1f4c8;Python for finance series) Warning: There is no magical formula or Holy Grail here, though a new world might open the door for you.警告 &#xff1a; 這里沒有神奇的配方或圣杯&#xff0c;盡管…

SQL Server 常用分頁SQL

今天無聊和朋友討論分頁&#xff0c;發現網上好多都是錯的。網上經常查到的那個Top Not in 或者Max 大部分都不實用&#xff0c;很多都忽略了Order和性能問題。為此上網查了查&#xff0c;順帶把2000和2012版本的也補上了。 先說說網上常見SQL的錯誤或者說局限問題 12345select…

Word中摘要和正文同時分欄后,正文跑到下一頁,怎么辦?或Word分欄后第一頁明明有空位后面的文字卻自動跳到第二頁了,怎么辦?...

問題1&#xff1a;Word中摘要和正文同時分欄后&#xff0c;正文跑到下一頁&#xff0c;怎么辦&#xff1f;或Word分欄后第一頁明明有空位后面的文字卻自動跳到第二頁了&#xff0c;怎么辦&#xff1f; 答&#xff1a;在word2010中&#xff0c;菜單欄中最左側選“文件”->“選…

leetcode 664. 奇怪的打印機(dp)

題目 有臺奇怪的打印機有以下兩個特殊要求&#xff1a; 打印機每次只能打印由 同一個字符 組成的序列。 每次可以在任意起始和結束位置打印新字符&#xff0c;并且會覆蓋掉原來已有的字符。 給你一個字符串 s &#xff0c;你的任務是計算這個打印機打印它需要的最少打印次數。…

SQL數據類型說明和MySQL語法示例

SQL數據類型 (SQL Data Types) Each column in a database table is required to have a name and a data type. 數據庫表中的每一列都必須具有名稱和數據類型。 An SQL developer must decide what type of data that will be stored inside each column when creating a tab…

PHP7.2 redis

為什么80%的碼農都做不了架構師&#xff1f;>>> PHP7.2 的redis安裝方法&#xff1a; 順便說一下PHP7.2的安裝&#xff1a; wget http://cn2.php.net/distributions/php-7.2.4.tar.gz tar -zxvf php-7.2.4.tar.gz cd php-7.2.4./configure --prefix/usr/local/php…

leetcode 1787. 使所有區間的異或結果為零

題目 給你一個整數數組 nums??? 和一個整數 k????? 。區間 [left, right]&#xff08;left < right&#xff09;的 異或結果 是對下標位于 left 和 right&#xff08;包括 left 和 right &#xff09;之間所有元素進行 XOR 運算的結果&#xff1a;nums[left] XOR n…

【JavaScript】網站源碼防止被人另存為

1、禁示查看源代碼 從"查看"菜單下的"源文件"中同樣可以看到源代碼&#xff0c;下面我們就來解決這個問題&#xff1a; 其實這只要使用一個含有<frame></frame>標記的網頁便可以達到目的。 <frameset> <frame src"你要保密的文件…

梯度 cv2.sobel_TensorFlow 2.0中連續策略梯度的最小工作示例

梯度 cv2.sobelAt the root of all the sophisticated actor-critic algorithms that are designed and applied these days is the vanilla policy gradient algorithm, which essentially is an actor-only algorithm. Nowadays, the actor that learns the decision-making …

共享語義 unix語義_語義UI按鈕

共享語義 unix語義什么是語義UI按鈕&#xff1f; (What are Semantic UI Buttons?) A button indicates a possible user action. Semantic UI provides an easy-to-use syntax that simplifies not only the styling of a button, but also the natural language semantics.按…

垃圾回收算法優缺點對比

image.pngGC之前 說明&#xff1a;該文中的GC算法講解不僅僅局限于某種具體開發語言。 mutator mutator 是 Edsger Dijkstra 、 琢磨出來的詞&#xff0c;有“改變某物”的意思。說到要改變什么&#xff0c;那就是 GC 對象間的引用關系。不過光這么說可能大家還是不能理解&…

標準C程序設計七---77

Linux應用 編程深入 語言編程標準C程序設計七---經典C11程序設計 以下內容為閱讀&#xff1a; 《標準C程序設計》&#xff08;第7版&#xff09; 作者&#xff1a;E. Balagurusamy&#xff08;印&#xff09;&#xff0c; 李周芳譯 清華大學出版社…

leetcode 1190. 反轉每對括號間的子串

題目 給出一個字符串 s&#xff08;僅含有小寫英文字母和括號&#xff09;。 請你按照從括號內到外的順序&#xff0c;逐層反轉每對匹配括號中的字符串&#xff0c;并返回最終的結果。 注意&#xff0c;您的結果中 不應 包含任何括號。 示例 1&#xff1a; 輸入&#xff1a…

yolo人臉檢測數據集_自定義數據集上的Yolo-V5對象檢測

yolo人臉檢測數據集計算機視覺 (Computer Vision) Step by step instructions to train Yolo-v5 & do Inference(from ultralytics) to count the blood cells and localize them.循序漸進的說明來訓練Yolo-v5和進行推理(來自Ultralytics )以對血細胞進行計數并將其定位。 …

oauth2-server-php-docs 授權類型

授權碼 概觀 在Authorization Code交付式時使用的客戶端想要請求訪問受保護資源代表其他用戶&#xff08;即第三方&#xff09;。這是最常與OAuth關聯的授予類型。 詳細了解授權碼 用例 代表第三方來電履行 創建一個實例OAuth2\GrantType\AuthorizationCode并將其添加到您的服務…

flask框架視圖和路由_角度視圖,路由和NgModule的解釋

flask框架視圖和路由Angular vs AngularJS (Angular vs AngularJS) AngularJS (versions 1.x) is a JavaScript-based open source framework. It is cross platform and is used to develop Single Page Web Application (SPWA). AngularJS(版本1.x)是一個基于JavaScript的開源…

NGUI EventDelagate事件委托

using System.Collections; using System.Collections.Generic; using UnityEngine;public class BUttonClick : MonoBehaviour {public UIButton button_01;void Start(){if (button_01 null){Debug.Log("button組件丟失了");}else{//首先將腳本中的ClicktheButton…