当Apify Puppeteer Scraper运行超过了预设的超时时间,会出现错误信息“Apify Puppeteer Scraper 错误: Actor运行已达到超时时间”。解决这个问题的方法是增加超时时间或优化代码以减少运行时间。以下是一些示例代码和解决方法:
增加超时时间:
const Apify = require('apify');
Apify.main(async () => {
// 设置超时时间为60分钟
const timeout = 60 * 60 * 1000;
const browser = await Apify.launchPuppeteer({ timeout });
const page = await browser.newPage();
await page.goto('https://example.com');
await browser.close();
});
在上面的示例中,我们使用了Apify.launchPuppeteer
方法来启动一个Puppeteer浏览器,并通过timeout
参数设置了超时时间为60分钟。你可以根据需要自行调整超时时间。
优化代码以减少运行时间:
waitForNavigation
等方法来减少页面加载时间。const Apify = require('apify');
Apify.main(async () => {
const browser = await Apify.launchPuppeteer();
const page = await browser.newPage();
await page.goto('https://example.com');
// 禁用图片加载
await page.setRequestInterception(true);
page.on('request', (req) => {
if (req.resourceType() === 'image') {
req.abort();
} else {
req.continue();
}
});
// 使用选择器定位元素
const title = await page.$eval('h1', (element) => element.textContent);
console.log(title);
await browser.close();
});
在上面的示例中,我们通过setRequestInterception
方法禁用了图片加载,使用了选择器h1
来定位页面中的标题,从而减少了页面加载时间和代码复杂度。
通过增加超时时间或优化代码,你可以解决“Apify Puppeteer Scraper 错误: Actor运行已达到超时时间”的问题。根据具体情况选择合适的解决方法。
上一篇:Apify API 请求体