问题
None of the existing Q&As have a clean solution for this question, e.g.,
- puppeteer wait for page update after button click (no navigation)
- How can I wait for network idle after click on an element in puppeteer?
So here is a simple working example for people to see/try/fix:
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch({headless: true});
try {
const page = await browser.newPage();
await page.setViewport({width: 800,height: 800});
const response = await page.goto(`https://stock.finance.sina.com.cn/usstock/quotes/TSLA.html`, {
waitUntil: 'networkidle0'
});
//console.log(await page.content());
let selector = `div.kke_menus_tab_edage > div:nth-child(6) > a`
await page.waitForSelector(selector)
await page.click(selector)
const inputElement = await page.$('div.sec.clearfix div.block.block_hq')
await inputElement.screenshot({path: 'sina-finance.png'})
} catch (err) {console.log(err.message);}
finally {
await browser.close();
}
})()
So, in summary,
- The
click
does not trigger any navigation - The
inputElement
already exist, even before clicking so can't wait on that.
Any simple solution like page.waitForNavigation
, e.g., page.waitForNetwork({waitUntil: 'networkidle0'})
?
Else, I'll raise a bug to the puppeteer project to provide one. Thx.
回答1:
If you know the specific request being made when you click the button, you can easily use the page.waitForResponse()
method.
e.g.
const pageClick = page.click(selector);
const response = page.waitForResponse(response => response.url() === 'https://example.com' && response.status() === 200);
await Promise.all([
pageClick,
response
]);
来源:https://stackoverflow.com/questions/59831875/puppeteer-wait-for-network-idle-after-click