有什么方法可以等待在puppeteer中的page.click()之后添加动态内容吗



我一直在写一段代码,它会刮擦开拓者网站。该网站是一个动态网站,因此当我单击显示更多按钮时,它会加载用户拥有的其他徽章。那么,有没有一种方法可以让我点击该按钮,然后等待添加新内容,然后在cheerio中加载标记进行抓取。

目前,我只是让浏览器在重新点击之前等待3秒钟,但这会使整个过程花费大量时间,如果浏览器在这段时间内无法获取,也可能会失败。

那么,还有其他选择吗?请在下面找到我的代码-->

const url = "https://trailblazer.me/id/akganesa";
// function to load the page
async function getPage() {
const browser = await puppeteer.launch({headless: true});
const page = await browser.newPage();
await page.goto(url, {waitUntil: 'networkidle0'});
const [first_button] = await page.$x("//button[contains(., 'Show More')]");
await first_button.click();
while (
(await (await page.$x("//button[contains(., 'Show More')]")).length) > 0
) {
const [button] = await page.$x("//button[contains(., 'Show More')]");
await button.click();
await page.waitForResponse(response => response.status() === 200);
}
const html = await page.content(); // serialized HTML of page DOM.
await browser.close();
return html;
}
// using cheerio to scrape
const html = await getPage();
const $ = cheerio.load(html);

下面的代码可以满足您的要求。我之所以让它在进入while循环之前点击[first_button],是因为第一个"显示更多"按钮实际上并没有发出网络请求。

const go = async () => {
const browser = await puppeteer.launch({
headless: false,
args: [
"--no-sandbox",
"--disable-setuid-sandbox",
"--window-size=1600,1200"
],
defaultViewport: null
});
const context = await browser.createIncognitoBrowserContext();
const page = await context.newPage();
try {
await page.goto("https://trailblazer.me/id/akganesa", {
waitUntil: "networkidle2"
});
const [first_button] = await page.$x("//button[contains(., 'Show More')]");
await first_button.click();
while (
(await (await page.$x("//button[contains(., 'Show More')]")).length) > 0
) {
const [button] = await page.$x("//button[contains(., 'Show More')]");
await button.click();
await page.waitForResponse(response => response.status() === 200);
}
browser.close();
return;
} catch (err) {
console.log(err);
browser.close();
return;
}
};
go();

最新更新