问题
How can I make a function that waits until a certain CSS selector loads in puppeteer?
I want to refresh the page over and over until the '.product-form__add-to-cart' is present, then I want it to continue on with the code.
回答1:
The corresponding puppeteer method is page.waitForSelector.
Example:
await page.waitForSelector('.product-form__add-to-cart')
But if you need to reload the page to get the desired element (maybe because the site you are visiting can look different between visits) than you can just check if the element is present in the DOM after the page is rendered and if not: then you can try to page.reload it.
await page.goto(url, { waitUntil: 'domcontentloaded' })
const selectorExists = await page.$('.product-form__add-to-cart')
if (selectorExists !== null) {
// do something with the element
} else {
await page.reload({ waitUntil: 'domcontentloaded' })
}
You can do it in a loop as well, where you break if the selector appears, but be careful: if it never shows up you will end up in an endless loop! Set a maximum number of tries.
Edit
If you are sure about running it in a loop until the selector appears: then you can try with a while loop:
await page.goto(url, { waitUntil: 'domcontentloaded' })
let selectorExists = await page.$('.product-form__add-to-cart')
while (selectorExists === null) {
await page.reload({ waitUntil: 'domcontentloaded' })
selectorExists = await page.$('.product-form__add-to-cart')
}
// if condition meets the script will go on
As I said earlier: you can end up with an endless loop like this, so be careful.
来源:https://stackoverflow.com/questions/62736740/how-can-i-make-a-monitoring-function-to-wait-for-an-html-element-in-puppeteer