https://pptr.dev/ puppeteer
https://blog.appsignal.com/2023/02/08/puppeteer-in-nodejs-common-mistakes-to-avoid.html
Bear in mind that if click() triggers a navigation event and there's a separate page.waitForNavigation() promise to be resolved, you may end up with a race condition that yields unexpected results. The correct pattern for click and wait for navigation is the following
# M 1
const navigationPromise = page.waitForNavigation();
await page.click("#submit");
await navigationPromise;
# M 2
await Promise.all([
page.waitForNavigation(),
page.click("#submit"),
]);
const [response] = await Promise.all([
page.waitForNavigation(waitOptions),
page.click(selector, clickOptions),
]);
HTMLElement.click()
await page.goto(url);
await elementHandle.click();
await page.click('input[type=submit]');
await page.waitForNavigation();
await page.setDefaultNavigationTimeout(0);
process.exit(0);
// frame有点类似page
elementHandle = await page.waitForSelector(selector, {visible: true})
elementHandle = await page.waitForSelector(selector) 返回: <Promise<ElementHandle>>
elementHandle = await page.$(selector) 返回: <Promise<?ElementHandle>>
elementHandle = await page.$$(selector) 返回: <Promise<Array<ElementHandle>>>
elementHandle = await page.evaluateHandle();
element = await page.$eval();
// 获取Dom节点属性
text = await page.evaluate(el => el.textContent, elementHandle);
text = await elementHandle.evaluate(el => el.textContent);
element = await page.evaluate(() => {
return document.querySelector(selector);
return document.querySelector(selector).textContent;
});
Node.js Puppeteer: 点击事件与waitForNavigation正确用法
在使用Node.js的Puppeteer库时,需要注意点击操作可能触发的导航事件。为了避免race条件导致的意外结果,正确处理click和waitForNavigation的方法是同步进行。例如,可以使用`navigationPromise`等待导航完成,或者使用`Promise.all`同时处理点击和导航。此外,本文还介绍了如何使用`page.goto`、`elementHandle.click`、`page.waitForSelector`等方法,以及获取DOM节点属性的技巧。
2136

被折叠的 条评论
为什么被折叠?



