Advertisement
Guest User

Express + Puppeteer example

a guest
Aug 15th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require('express')
  2. const puppeteer = require('puppeteer')
  3.  
  4. class InstagramClient {
  5.   async start() {
  6.     this.browser = await puppeteer.launch({
  7.       headless: true //When set to true, a new browser window will ge opened
  8.     })
  9.   }
  10.  
  11.   async stop() {
  12.     await this.browser.close()
  13.   }
  14.  
  15.   async getFollowers(username) {
  16.     if (!this.browser) throw new Error('Browser not started')
  17.  
  18.     const page = await this.browser.newPage()
  19.     await page.goto(`https://instagram.com/${username}/`)
  20.  
  21.     const pageExists = await page.evaluate(_ => {
  22.       return document.querySelector('.error-container') === null
  23.     })
  24.     if (!pageExists) {
  25.       throw new Error(`Page of ${username} doesn't exist`)
  26.    }
  27.  
  28.    //Wait until the page got completly renderer
  29.    await page.waitForSelector('h1')
  30.  
  31.    const followers = await page.evaluate(username => {
  32.      //This code will get executed on the instagram page
  33.  
  34.      //Get the number of followers
  35.      const followers = document.querySelector(`a[href="/accounts/login/?next=%2F${username}%2Ffollowers%2F&source=followed_by_list"]`).querySelector('span').innerText
  36.      //Return the number of followers back to the node process
  37.      return followers
  38.    }, username)
  39.  
  40.    page.close()
  41.  
  42.    return followers
  43.  }
  44. }
  45.  
  46. const client = new InstagramClient()
  47. const app = express()
  48.  
  49. app.get('/:instagramName/followers', async (request, response) => {
  50.  const instagramName = request.params.instagramName
  51.  try {
  52.    const followers = await client.getFollowers(instagramName)
  53.    response.json({
  54.      success: true,
  55.      followers: followers
  56.    })
  57.  } catch (e) {
  58.    response.json({
  59.      success: false,
  60.      error: e.toString()
  61.    })
  62.    return
  63.  }
  64. })
  65.  
  66. async function start() {
  67.  const PORT = 3000
  68.  await client.start()
  69.  app.listen(PORT, _ =>
  70.    console.log(`Server is listening on port ${PORT}
  71. Goto http://localhost:${PORT}/teslamotors/followers to try it out`)
  72.  )
  73. }
  74.  
  75. start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement