相关文章
Puppeteer性能优化与执行速度提升 | 我是大熊 (it2048.cn)
看点:
- 指出了 Chromium 启动参数列表 出处
- 简洁的阐述了为什么要这样优化,而不是粗暴的扔代码
- 指出了选择了合适的无头浏览器版本也能优化性能
$ yum install chromium-headless
$ /usr/lib64/chromium-browser/headless_shell (调用路径)
使用 generic-pool 优化 puppeteer 并发问题 - 知乎 (zhihu.com)
看点:
- 指出了通过 generic-pool 连接池,来复用浏览器实例,虽然,puppeteer本身能通过
browser.wsEndpoint()方式复用,但puppeteer官方也不推荐此方式。而池化貌似是比较可靠的方式 - 并还指出了一些其他性能问题(与爬虫相关的)
代码来自: GitHub - binded/phantom-pool: PhantomJS resource pool based on generic-pool
import phantom from 'phantom'
import genericPool from 'generic-pool'
// import initDebug from 'debug'
// const debug = initDebug('phantom-pool')
const initPhantomPool = ({
max = 10,
// optional. if you set this, make sure to drain() (see step 3)
min = 2,
// specifies how long a resource can stay idle in pool before being removed
idleTimeoutMillis = 30000,
// specifies the maximum number of times a resource can be reused before being destroyed(指定资源在被销毁之前可以重用的最大次数, 避免浏览器实例长期使用导致的性能问题)
maxUses = 50,
testOnBorrow = true,
phantomArgs = [],
validator = () => Promise.resolve(true),
...otherConfig
} = {}) => {
// TODO: randomly destroy old instances to avoid resource leak?
const factory = {
create: () => phantom.create(...phantomArgs)
.then(instance => {
instance.useCount = 0
return instance
}),
destroy: (instance) => instance.exit(),
validate: (instance) => validator(instance)
.then(valid => Promise.resolve(valid && (maxUses <= 0 || instance.useCount < maxUses))),
}
const config = {
max,
min,
idleTimeoutMillis,
testOnBorrow,
...otherConfig,
}
const pool = genericPool.createPool(factory, config)
const genericAcquire = pool.acquire.bind(pool)
pool.acquire = () => genericAcquire().then(r => {
r.useCount += 1
return r
})
pool.use = (fn) => {
let resource
return pool.acquire()
.then(r => {
resource = r
return resource
})
.then(fn)
.then((result) => {
pool.release(resource)
return result
}, (err) => {
pool.release(resource)
throw err
})
}
return pool
}
// To avoid breaking backwards compatibility
// https://github.com/binded/phantom-pool/issues/12
initPhantomPool.default = initPhantomPool
export default initPhantomPool
爬虫利器 Puppeteer 的一些最佳实践 - 知乎 (zhihu.com)
看点
- 该文章指出应该用docker跑puppeteer服务,因为puppeteer太占资源,可能容易挂掉,从而导致部署在相同机器的其他服务也出现问题,而docker能在此时避免puppeteer服务挂掉,产生的关联风险
- 同时指出用Playwright代替puppeteer,因为Playwright支持更多的浏览器,以及更多情况
- 同时不建议直接使用无头浏览器方案,而是使用 fetch抓取网页源码,使用 Cheerio 解析html内容,遗憾的是 Cheerio 只能遍历/操作解析后的html, 并没有执行js的能力,如果你需要执行js能力, Cheerio 让你选其他工具:如: puppeteer, Playwright, jsdom/jsdom
- 并提及了启用浏览器的
user-data-dir特性,使浏览器能直接从本地缓存读取资源,减少网络请求。不过这也有副作用,那就是会占用更多的磁盘空间,以及会使得cookie也保存下来,cookie可能标识了一个用户,那如果你不希望有这个特点,那最好还是不要启用user-data-dir特性
Puppeteer之如何提升脚本稳定性_js爬虫 puppeteer稳定性-CSDN博客
看点
- 这个是在单元测试中使用puppeteer, 重点是他实现了异常重试
优化 puppeteer - Sea's Blog (mrseawave.github.io)
看点
- 这篇是评论的价值更大,之前没有意识到,程序中并没有关闭浏览器的方法,看了评论之后,才意识到
Puppeteer自动化的性能优化与执行速度提升-CSDN博客
看点
- 这个是爬虫方向,应用Puppeteer的注意事项,虽然,我无意搞爬虫,但这里面说的
平滑重启,感觉有点用,虽然,暂时不知道如何实现平滑重启