puppeteer 等待第一个元素加载

编程入门 行业动态 更新时间:2024-10-15 22:24:11
本文介绍了puppeteer 等待第一个元素加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试检查要加载到我的页面中的第一个元素类以执行我的代码.例如,我的页面可以有 3 种不同的状态,它可以具有类 .a 的弹出窗口,或者具有类 .b 的页面或类 .b 的页面代码>.c.所以我想等待其中一个加载并先加载哪个.我尝试使用 Promise.race 来做到这一点.我的代码:

I'm trying to check the first element class to load in my page to execute my code. For example, my page can have 3 different states, it can have a popup with class .a or it can have a page with class .b or a page with class .c. So I would like to wait one of them to load and get which one loaded first. I tried to do it with Promise.race. My code:

await page.goto('myurl', { waitUntil: 'networkidle2', timeout: 30000 }).then(async () => { await Promise.race([ page.waitForSelector('.a'), page.waitForSelector('.b'), page.waitForSelector('.c'), ], {timeout: 60000 }) console.log('done loading one of the 3 elements') }).catch(e => { console.log(e) })

但在那之后,我得到一个错误,例如类 .b 无法在 60000 毫秒内加载.不是应该工作吗?Promise.race 在其中一个执行后仍在运行.我该如何解决这个问题?

But after that, I get en error that for example class .b could not load in 60000ms. Isnt it supposed to work? Promise.race is still running after one of them executed. How can I solve this?

推荐答案

我在 doc 其中 Promise.race() 需要一个 {timeout: ...}论证.

I can't find a place in the doc where Promise.race() takes a {timeout: ...} argument.

如果你想设置超时,我会在 Puppeteer 的 page.waitForSelector 中设置.

If you want to set a timeout, I would do it in the page.waitForSelector in Puppeteer.

await page.goto('stackoverflow/questions/53624870/puppeteer-waits-for-first-element-to-load', { waitUntil: 'networkidle2', timeout: 30000 }) .then(async () => { let elementHandle = await Promise.race([ page.waitForSelector('.post-text', {timeout: 60000}), page.waitForSelector('.should-fail', {timeout: 60000}), page.waitForSelector('.should-fail-2', {timeout: 60000}), ]); console.log(elementHandle != null); }) .catch(e => { console.log(e); });

而且,但这将是我个人的写作方式,我会等待一切,而不是像这样混合等待/然后:

And also, but that would be my personnal way of writing it, I would await everything and not mix await/then, like so :

await page.goto('stackoverflow/questions/53624870/puppeteer-waits-for-first-element-to-load', { waitUntil: 'networkidle2', timeout: 30000 }) .catch(e => console.error(e)); let elementHandle = await Promise.race([ page.waitForSelector('.post-text', {timeout: 60000}), page.waitForSelector('.should-fail', {timeout: 60000}), page.waitForSelector('.should-fail-2', {timeout: 60000}) ]); console.log(elementHandle != null);

更多推荐

puppeteer 等待第一个元素加载

本文发布于:2023-11-04 18:11:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1558656.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:第一个   加载   元素   puppeteer

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!