Puppeteer 2 Network throttling 网络节流,切换不同的网络环境
Posted on 六 09 十月 2021 in Puppeteer
网络节流
Chrome 浏览器 DevTools有个功能是网络节流,非常有用。 模拟不同的网络环境,预设了Fast 3G,Slow 3G,offline离线 也可以自己设定,下载速率,上传速率,延迟时间
Puppeteer支持
let NETWORK_PRESETS = {
'GPRS': {
'offline': false,
'downloadThroughput': 50 * 1024 / 8,
'uploadThroughput': 20 * 1024 / 8,
'latency': 500
},
'Regular2G': {
'offline': false,
'downloadThroughput': 250 * 1024 / 8,
'uploadThroughput': 50 * 1024 / 8,
'latency': 300
},
'Good2G': {
'offline': false,
'downloadThroughput': 450 * 1024 / 8,
'uploadThroughput': 150 * 1024 / 8,
'latency': 150
},
'Regular3G': {
'offline': false,
'downloadThroughput': 750 * 1024 / 8,
'uploadThroughput': 250 * 1024 / 8,
'latency': 100
},
'Good3G': {
'offline': false,
'downloadThroughput': 1.5 * 1024 * 1024 / 8,
'uploadThroughput': 750 * 1024 / 8,
'latency': 40
},
'Regular4G': {
'offline': false,
'downloadThroughput': 4 * 1024 * 1024 / 8,
'uploadThroughput': 3 * 1024 * 1024 / 8,
'latency': 20
},
'DSL': {
'offline': false,
'downloadThroughput': 2 * 1024 * 1024 / 8,
'uploadThroughput': 1 * 1024 * 1024 / 8,
'latency': 5
},
'WiFi': {
'offline': false,
'downloadThroughput': 30 * 1024 * 1024 / 8,
'uploadThroughput': 15 * 1024 * 1024 / 8,
'latency': 2
}
}
const puppeteer = require('puppeteer')
puppeteer.launch().then(async browser => {
// Create a new tab
const page = await browser.newPage()
// Connect to Chrome DevTools
const client = await page.target().createCDPSession()
// Set throttling property
await client.send('Network.emulateNetworkConditions', {
'offline': false,
'downloadThroughput': 200 * 1024 / 8,
'uploadThroughput': 200 * 1024 / 8,
'latency': 20
})
//或者
await client.send('Network.emulateNetworkConditions',NETWORK_PRESETS['Good3G'])
// Navigate and take a screenshot
await page.goto('https://fdalvi.github.io')
await page.screenshot({path: 'screenshot.png'})
await browser.close()
})