NewCode CLOUD — 20% off your first month on all cloud VPSClaim

Headless Browser Scraping on Hong Kong VPS: Playwright and Puppeteer (2026)

· 5 min read

Headless browsers — Chrome or Firefox running without a display — enable web scraping of JavaScript-rendered pages, automated testing, screenshot generation, PDF export, and website monitoring. Running Playwright or Puppeteer on a Hong Kong VPS places your headless browser close to mainland Chinese websites (30–50ms) and to Asia-Pacific market data sources, dramatically reducing scrape times compared to running from a US or EU server.


Use Cases

  • Scrape Chinese e-commerce platforms (Taobao, JD, Pinduoduo) with low latency
  • Monitor competitor pricing across Asia-Pacific marketplaces
  • Generate PDF invoices or reports from HTML templates
  • Take screenshots of web pages for archiving or thumbnails
  • Run end-to-end tests against your Hong Kong-hosted application
  • Automate form submissions or web workflows

Step 1: Install Dependencies

<code">apt update && apt install -y \
  chromium-browser \
  fonts-liberation \
  fonts-noto-cjk \        # Critical for Chinese character rendering
  libnss3 libatk1.0-0 libatk-bridge2.0-0 \
  libcups2 libdrm2 libxkbcommon0 libxcomposite1 \
  libxdamage1 libxfixes3 libxrandr2 libgbm1 \
  libasound2

curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt install -y nodejs

mkdir -p /var/www/scraper && cd /var/www/scraper
npm init -y

Step 2: Playwright Setup

<code"># Install Playwright (recommended — more stable than Puppeteer)
npm install playwright playwright-core

# Install browsers
npx playwright install chromium
npx playwright install-deps chromium

# Test
node -e "const { chromium } = require('playwright'); chromium.launch().then(b => { console.log('OK'); b.close(); })"

Step 3: Scraping Script

<code"># scraper.js — scrape a JavaScript-rendered page
const { chromium } = require('playwright')

async function scrapeProductList(url) {
  const browser = await chromium.launch({
    executablePath: '/usr/bin/chromium-browser',
    headless: true,
    args: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '--disable-dev-shm-usage',
      '--disable-gpu',
      '--single-process',          // Better for containerised/VPS environments
    ]
  })

  const context = await browser.newContext({
    userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
    viewport: { width: 1280, height: 720 },
    locale: 'zh-CN',
    timezoneId: 'Asia/Shanghai',
  })

  const page = await context.newPage()

  // Block images and fonts (faster scraping — we only need text/data)
  await page.route('**/*.{png,jpg,jpeg,gif,svg,webp,woff,woff2}', route => {
    route.abort()
  })

  try {
    await page.goto(url, {
      waitUntil: 'networkidle',    // Wait until no network requests for 500ms
      timeout: 30000,
    })

    // Wait for specific content to appear
    await page.waitForSelector('.product-list', { timeout: 10000 })

    // Extract data
    const products = await page.evaluate(() => {
      return Array.from(document.querySelectorAll('.product-item')).map(el => ({
        name: el.querySelector('.name')?.textContent?.trim(),
        price: el.querySelector('.price')?.textContent?.trim(),
        url: el.querySelector('a')?.href,
      }))
    })

    return products

  } finally {
    await context.close()
    await browser.close()
  }
}

// Run with rate limiting
async function scrapeWithDelay(urls, delayMs = 2000) {
  const results = []
  for (const url of urls) {
    const data = await scrapeProductList(url)
    results.push({ url, data, timestamp: new Date().toISOString() })
    console.log(`Scraped ${url}: ${data.length} items`)
    await new Promise(r => setTimeout(r, delayMs))  // Respectful delay between requests
  }
  return results
}

scrapeWithDelay(['https://example.com/products']).then(console.log)

Step 4: Screenshot and PDF Generation

<code"># Generate PDF invoice from HTML template
async function generatePDF(htmlContent, outputPath) {
  const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] })
  const page = await browser.newPage()

  await page.setContent(htmlContent, { waitUntil: 'networkidle' })
  await page.emulateMedia({ media: 'print' })

  await page.pdf({
    path: outputPath,
    format: 'A4',
    printBackground: true,
    margin: { top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' }
  })

  await browser.close()
  console.log(`PDF saved: ${outputPath}`)
}

// Generate screenshot for Open Graph preview or archival
async function takeScreenshot(url, outputPath) {
  const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] })
  const page = await browser.newPage()
  await page.setViewportSize({ width: 1200, height: 630 })  // OG image size
  await page.goto(url, { waitUntil: 'networkidle' })
  await page.screenshot({ path: outputPath, type: 'png', fullPage: false })
  await browser.close()
}

Step 5: Scraping API Service

<code"># API server that accepts scrape requests — integrates with your application
const express = require('express')
const { chromium } = require('playwright')

const app = express()
app.use(express.json())

// Reuse browser instance for efficiency
let browser = null

async function getBrowser() {
  if (!browser || !browser.isConnected()) {
    browser = await chromium.launch({
      headless: true,
      args: ['--no-sandbox', '--disable-dev-shm-usage', '--single-process']
    })
  }
  return browser
}

app.post('/scrape', async (req, res) => {
  const { url, selector, waitFor } = req.body
  if (!url) return res.status(400).json({ error: 'URL required' })

  const b = await getBrowser()
  const context = await b.newContext()
  const page = await context.newPage()

  try {
    await page.goto(url, { waitUntil: 'networkidle', timeout: 30000 })
    if (waitFor) await page.waitForSelector(waitFor)

    const content = selector
      ? await page.$eval(selector, el => el.textContent)
      : await page.content()

    res.json({ url, content, scraped_at: new Date() })
  } catch (err) {
    res.status(500).json({ error: err.message })
  } finally {
    await context.close()
  }
})

app.post('/screenshot', async (req, res) => {
  const { url } = req.body
  const b = await getBrowser()
  const page = await b.newPage()
  await page.setViewportSize({ width: 1280, height: 800 })
  await page.goto(url, { waitUntil: 'networkidle' })
  const buffer = await page.screenshot({ type: 'png' })
  await page.close()
  res.type('image/png').send(buffer)
})

app.listen(4000, '127.0.0.1', () => console.log('Scraping API on :4000'))

Step 6: Schedule Recurring Scrapes

<code"># package.json (add node-cron)
# npm install node-cron

const cron = require('node-cron')

// Scrape competitor prices every hour
cron.schedule('0 * * * *', async () => {
  console.log('Starting hourly price scrape...')
  const prices = await scrapeProductList('https://competitor-site.com/products')
  await savePricesToDB(prices)  // Save to your PostgreSQL
  console.log(`Price update: ${prices.length} products saved`)
})

// Daily screenshot archive at midnight HKT
cron.schedule('0 0 * * *', { timezone: 'Asia/Hong_Kong' }, async () => {
  const date = new Date().toISOString().split('T')[0]
  await takeScreenshot('https://yourdomain.com', `/var/archives/${date}.png`)
})

Resource Optimisation

<code"># Playwright context reuse — most important for throughput
# Create one browser, many contexts (contexts are like incognito windows)

const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] })

// Parallel scraping with a pool of contexts
async function scrapeInParallel(urls, concurrency = 3) {
  const semaphore = new Array(concurrency).fill(null)
  return Promise.all(
    urls.map(async url => {
      const context = await browser.newContext()
      const page = await context.newPage()
      try {
        await page.goto(url)
        const result = await page.evaluate(() => document.title)
        return { url, result }
      } finally {
        await context.close()  // Each context fully isolated; close after use
      }
    })
  )
}
RAM on VPS Concurrent browsers Use case
2 GB 2–3 Light scraping, PDF generation
4 GB 5–8 Regular scraping, screenshot service
8 GB 15–20 Heavy scraping, parallel test runs

Conclusion

Playwright on a Hong Kong VPS places your headless browser close to Asia-Pacific websites — scraping Chinese e-commerce platforms at 30–50ms round-trip versus 200–400ms from a US server. Chinese character rendering works out of the box with the fonts-noto-cjk package. The scraping API pattern decouples your main application from browser automation overhead, and a browser context pool enables parallel scraping without excessive RAM consumption.

Automate from Asia: Browse Server.HK Hong Kong VPS plans — a 4 GB plan runs 5–8 concurrent Playwright browsers for most scraping and automation workloads.

Related articles

More in VPS & ServersServer setup guides