【工具】Puppeteer爬取图片

Puppeteer 是 Chrome 开发团队在 2017 年发布的一个 Node.js 包,用来模拟 Chrome 浏览器的运行
官网
中文

const puppeteer = require('puppeteer')
const fs = require('fs')
var request = require('request')

// 下载图片
var download = function(uri, filename, callback){
    request.head(uri, function(err, res, body){
        request(uri)
            .pipe(fs.createWriteStream(__dirname + `/imgs/${filename}`))
            .on('close', function(){
                console.log('Finish Copy Images')
            })
    })
}

// 等一下
function wait(ms){
    return new Promise(resolve => setTimeout(()=> resolve(), ms))
}

;(async()=>{
    const browser = await puppeteer.launch({
        // headless: false, //  false 启动完整版本的浏览器 true 关闭无头模式 ,对查看浏览器显示的内容很有用
        // slowMo: 100 // slowMo 选项会将 Puppeteer 操作浏览器减慢指定的毫秒数
    })

    const page = await browser.newPage()
    await page.goto('http://baijiahao.baidu.com/s?id=1704795850072632109', {
        waitUntil: 'domcontentloaded'
    })

    // Get the height of the rendered page
    const bodyHandle = await page.$('body')
    const { height } = await bodyHandle.boundingBox()
    await bodyHandle.dispose()

    // Scroll one viewport at a time, pausing to let content load
    const viewportHeight = page.viewport().height
    let viewportIncr = 0
    while(viewportIncr + viewportHeight < height){
        await page.evaluate(_viewportHeight =>{
            window.scrollBy(0, _viewportHeight)
        }, viewportHeight)
        await wait(20)
        viewportIncr = viewportIncr + viewportHeight
    }

    // Scroll back to top
    await page.evaluate(_=>{
        window.scrollTo(0, 0)
    })

    // Some extra delay to let images load
    await wait(1000)

    let imageLink = await page.evaluate(()=>{
        const images = Array.from(document.querySelectorAll('img'))
        return images.map(img=>img.src)
        .filter(imgText=>imgText.includes('jpeg?token'))
    })

    console.log(imageLink)

    imageLink.forEach((img, index)=>{
        download(img, index+'.jpg', function(){
            console.log('done')
        })
    })

    // 监听控制台事件
    // page.on('console', msg => console.log('PAGE LOG:', msg.text()));

    await browser.close()

})()

更多Puppeteer例子

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值