//爬取百度高清图片
const phantom = require('phantom')
const express = require('express');
const app = express();
const fs= require('fs');
const cheerio = require('cheerio');
const request = require('request')
let server = app.listen(2000, function () {
let host = server.address().address;
let port = server.address().port;
console.log('Your App is running at http://%s:%s', host, port);
}); class stealData { constructor() {
// this.base_url = 'https://image.baidu.com/search/index?tn=baiduimage&ct=201326592&lm=-1&cl=2&ie=gb18030&word=%B6%AF%C2%FE%B1%DA%D6%BD&fr=ala&ala=1&pos=0&alatpl=wallpaper&oriquery=%E5%8A%A8%E6%BC%AB%E5%A3%81%E7%BA%B8'; //要爬取的网站
// this.base_url = 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&hs=0&xthttps=111111&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%8A%A8%E6%BC%AB+%E5%A3%81%E7%BA%B8&oq=%E5%8A%A8%E6%BC%AB+%E5%A3%81%E7%BA%B8&rsp=-1'
this.base_url = 'https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=index&fr=&hs=0&xthttps=111111&sf=1&fmq=&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E5%8A%A8%E6%BC%AB+%E5%A3%81%E7%BA%B8&oq=%E5%8A%A8%E6%BC%AB+%E5%A3%81%E7%BA%B8&rsp=-1' this.current_page = 1;
this.result_list = [];
this.a=''
}
async init() {
const instance = await phantom.create();//创建一个实例
try {
await this.openNet()//打开网页
await this.getLoadPictures();//获取高清图片地址
await this.imgSave(0);//下载图片
await instance.exit()//图片下完之后退出phantomjs环境
} catch (e) {
console.log(e);
}
} sleep(time) {
return new Promise((resolve) => {
console.log(`自动睡眠中,${time / 1000}秒后重新发送请求......`)
setTimeout(() => {
resolve();
}, time);
});
}//请求延迟时间,防止ip被封
delay(second) {
return new Promise((resolve) => {
setTimeout(resolve, second * 1000);
});
}//延迟时间
async openNet(){
await this.pageScroll(0)
} async pageScroll(i) {
const instance = await phantom.create();//创建一个实例
const page = await instance.createPage();
const that = this
const status = await page.open(this.base_url);//打开网站,返回的是一个状态
//网页加载的初始浏览器窗口大小
const size = await page.property('viewportSize', {
width: 1920,
height: 1080
})
await that.delay(5)
//滚动浏览器
await page.property('scrollPosition', {
left: 0,
top: 1000 * i
}) let content = await page.property('content')//获取dom元素
let $ = cheerio.load(content)
console.log($('.imgbox').length)
//如果图片数量少于20个 就一直往下滚
if($('.imgbox').length < 20) {
await this.pageScroll(++i)//回调自己 知道满足条件。也可使用for循环 可能速度有点慢
}
//所有的存储图片的dom元素都放在这里面
this.a = $('.imgitem')
}
//获取到缩略图集合
async getLoadPictures(a) {
const result_list = [];
let instance = await phantom.create();
let page = await instance.createPage();
let content = await page.property('content')
// let status = await page.open(this.base_url)
let $ = cheerio.load(content)
const that = this
//把所有的高清大图链接都统计起来
this.a.each((index, element) => {
result_list.push({
// title: $(element).find('.imgbox a').text(),
down_loda_url: ('https://image.baidu.com'+$(element).find('a').attr('href'))
});
});
that.result_list.push(...result_list);
// console.log('that.result_list',that.result_list[0])
}
//取到高清图链接 下载
async imgSave(i) {
let instance = await phantom.create();
let page = await instance.createPage();
let status = await page.open(this.result_list[i].down_loda_url)//打开高清大图链接
await this.delay(2)
let content = await page.property('content')
let $ = cheerio.load(content)
let src = $('#currentImg').attr('src')//获取高清大图的链接
console.log('statue',status)
console.log('src',src)
this.save(src,i)//保存图片
if(i<this.result_list.length) {
await this.imgSave(++i)//回掉自己 保存下一张图片。也可通过for循环 取到所有大图的链接 再集中下载 可能速度有点慢 }
}
//保存图片函数
save(url,i) {
console.log(`开始写入第${i+1}张`)
let ext = url.split('.').pop()
request(url).pipe(fs.createWriteStream(`./image/${new Date().getTime()}.${ext}`));
console.log(`写入成功`)
} } const thief = new stealData('xxx_url');
thief.init();

做了一些优化

//爬取百度高清图片
const phantom = require('phantom')
const express = require('express');
const app = express();
const fs= require('fs');
const cheerio = require('cheerio');
const request = require('request')
let server = app.listen(2000, function () {
let host = server.address().address;
let port = server.address().port;
console.log('Your App is running at http://%s:%s', host, port);
}); class stealData { constructor() {
this.base_url = 'https://image.baidu.com/search/index?ct=201326592&z=&tn=baiduimage&word=%E6%BC%AB%E5%A8%81%E5%9B%BE%E7%89%87&pn=0&ie=utf-8&oe=utf-8&cl=2&lm=-1&fr=ala&se=&sme=&width=1920&height=1080'
this.current_page = 1;
this.result_list = [];
this.a='';
this.urllist = []
}
async init() {
const instance = await phantom.create();//创建一个实例
try {
await this.openNet()//打开网页
await this.getLoadPictures();//获取缩略图图片地址
await this.getrealPictures();//获取高清图片地址并下载
} catch (e) {
console.log(e);
}
} sleep(time) {
return new Promise((resolve) => {
console.log(`自动睡眠中,${time / 1000}秒后重新发送请求......`)
setTimeout(() => {
resolve();
}, time);
});
}//请求延迟时间,防止ip被封
delay(second) {
return new Promise((resolve) => {
setTimeout(resolve, second * 1000);
});
}//延迟时间
async openNet(){
await this.pageScroll(0)
} async pageScroll(i) {
const instance = await phantom.create();//创建一个实例
const page = await instance.createPage();
const that = this
const status = await page.open(this.base_url);//打开网站,返回的是一个状态
//网页加载的初始浏览器窗口大小
const size = await page.property('viewportSize', {
width: 1920,
height: 1080
})
await that.delay(5)
//滚动浏览器
await page.property('scrollPosition', {
left: 0,
top: 1000 * i
}) let content = await page.property('content')//获取dom元素
let $ = cheerio.load(content)
console.log($('.imgbox').length)
//如果图片数量少于20个 就一直往下滚
if($('.imgbox').length < 20) {
await this.pageScroll(++i)//回调自己 知道满足条件。也可使用for循环 可能速度有点慢
}
//所有的存储图片的dom元素都放在这里面
this.a = $('.imgitem')
}
//获取到缩略图集合
async getLoadPictures(a) {
const result_list = [];
let instance = await phantom.create();
let page = await instance.createPage();
let content = await page.property('content')
let $ = cheerio.load(content)
const that = this
//把所有的缩略图链接都统计起来
this.a.each((index, element) => {
result_list.push({
// title: $(element).find('.imgbox a').text(),
down_loda_url: ('https://image.baidu.com'+$(element).find('a').attr('href'))
});
});
that.result_list.push(...result_list);
}
//取到每一个缩略图对应高清图链接并下载
async getrealPictures() {
let instance = await phantom.create();
let page = await instance.createPage();
for(let i=0;i<this.result_list.length;i++){
try {
let content = await page.property('content')
let status = await page.open(this.result_list[i].down_loda_url)
await this.delay(2)
let $ = cheerio.load(content)
let src = $('#currentImg').attr('src')//获取高清大图的链接
let ext = src.split('.').pop()
console.log('src',src)
console.log(`开始写入第${i+1}张`)
await request(src).pipe(fs.createWriteStream(`./Marvel/${new Date().getTime()}.${ext}`));
await this.sleep(3000)//防止被封
console.log(`写入成功`)
if(i==this.result_list.length-1){
console.log('跳出下载')
instance.exit()
}
}catch (e) {
console.log('errorheyu:',e)
} } } } const thief = new stealData('xxx_url');
thief.init();

参考:1、分分钟教你用node写个爬虫

   2、Node.js爬虫实战,爬去图片到本地

   3、爬取瀑布流网页高清图

   4、PhantomJs的用法

   5、NodeJs优秀工具之——nightmare

   6、腾讯云上Phantom用例

Node.js爬取百度图片瀑布流,使用class类封装。的更多相关文章

  1. node.js爬取数据并定时发送HTML邮件

    node.js是前端程序员不可不学的一个框架,我们可以通过它来爬取数据.发送邮件.存取数据等等.下面我们通过koa2框架简单的只有一个小爬虫并使用定时任务来发送小邮件! 首先我们先来看一下效果图 差不 ...

  2. selenium+chrome浏览器驱动-爬取百度图片

    百度图片网页中中,当页面滚动到底部,页面会加载新的内容. 我们通过selenium和谷歌浏览器驱动,执行js,是浏览器不断加载页面,通过抓取页面的图片路径来下载图片. from selenium im ...

  3. 百度图片爬虫-python版-如何爬取百度图片?

    上一篇我写了如何爬取百度网盘的爬虫,在这里还是重温一下,把链接附上: http://www.cnblogs.com/huangxie/p/5473273.html 这一篇我想写写如何爬取百度图片的爬虫 ...

  4. python 3 爬取百度图片

    python 3 爬取百度图片 学习了:https://blog.csdn.net/X_JS612/article/details/78149627

  5. Python 爬虫实例(1)—— 爬取百度图片

    爬取百度图片  在Python 2.7上运行 #!/usr/bin/env python # -*- coding: utf-8 -*- # @Author: loveNight import jso ...

  6. python爬虫-爬取百度图片

    python爬虫-爬取百度图片(转) #!/usr/bin/python# coding=utf-8# 作者 :Y0010026# 创建时间 :2018/12/16 16:16# 文件 :spider ...

  7. Python爬虫:通过关键字爬取百度图片

    使用工具:Python2.7 点我下载 scrapy框架 sublime text3 一.搭建python(Windows版本) 1.安装python2.7 ---然后在cmd当中输入python,界 ...

  8. python爬虫之爬取百度图片

    ##author:wuhao##爬取指定页码的图片,如果需要爬取某一类的所有图片,整体框架不变,但需要另作分析#import urllib.requestimport urllib.parseimpo ...

  9. Node.js爬取豆瓣数据

    一直自以为自己vue还可以,一直自以为webpack还可以,今天在慕课逛node的时候,才发现,自己还差的很远.众所周知,vue-cli基于webpack,而webpack基于node,对node不了 ...

  10. Java爬取 百度图片Google图片Bing图片

    先看看抓取的结果. 8个Java类: Startup.java - main函数 ImageCrawler.java - Crawler基类 BaiduImageCrawler.java - 百度图片 ...

随机推荐

  1. 笔记:vue.nextTick()方法的使用详解

    vue.nextTick定义: 在下次DOM更新循环结束之后执行延迟回调.在修改数据之后立即使用这个方法,获取更新后的DOM. 简单理解:数据更新了,在dom渲染后立即执行该函数 举例 注意:Vue实 ...

  2. CDH命令

    1.检查http服务是否开启 systemctl status httpd.service 本次没有开启是因为删了Log日志 通过查看http状态发现里面有个引用问题 重新建一个空的Log文件夹重启服 ...

  3. 3月1日Android开学学习

    Android开发的简单控件 1.文本显示 2.视图基础 3.常用布局 4.按钮触控 5.图像显示 文本显示 (1)设置文本内容 1.在XML文件中通过属性Android:text设置文本 Andro ...

  4. Python抓取数据具体流程

    之前看了一段有关爬虫的网课深有启发,于是自己也尝试着如如何过去爬虫百科"python"词条等相关页面的整个过程记录下来,方便后期其他人一起来学习. 抓取策略 确定目标:重要的是先确 ...

  5. BubbleSort,冒泡排序,C++非递归和递归实现

    1 // g++ bubble_sort.cc -Wall -O3 && ./a.exe 2 3 4 #include <iostream> 5 #include < ...

  6. ubuntu安装软件报依赖关系错误

    1.环境 Distributor ID: UbuntuDescription: Ubuntu 20.04.1 LTSRelease: 20.04Codename: focal 2.安装 报错 3.解决 ...

  7. jsp第4个作业(2)

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"% ...

  8. Unity 导出设置iOS 项目

    别人的代码 xcode打包部分设置的脚本如下 public class XcodeSetting : MonoBehaviour { private static List<Menu> m ...

  9. 代理模式_v1

    代理模式 概念: 1.真实对象:要被代理的对象 2.代理对象 3.代理模式 : 代理对象代理真实对象,达到增强真实对象功能的作用 实现方式: 1.静态代理:有一个类文件描述代理模式 2.动态代理:在内 ...

  10. Lombok和MapStruct冲突

    Lombok和MapStruct冲突导致无法生成正确的class文件. lombok自动生成getset等冗余代码. MapStruct对象copy.传统的BeanUtils.copy等利用的反射原理 ...