- 您发布了
getContent 的定义,而不是searchTarget。
- 您将
searchTarget 的结果传递给setInterval,而不是传递对函数searchTarget 的引用。
- 您说您遇到了错误,但没有说明这些错误是什么。
- 您可以使用
async function 和setInterval。
- 您不需要将
await 与console.log 一起使用(您不应使用await,因为console.log 不会返回任何内容,更不用说Promise<T>)。
我假设你真正想要的是:
async function getContent() {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
const content = await page.content();
console.log(content);
await browser.close();
}
const timerId = window.setInterval( getContent, 13 * 1000 );
// You can call `window.clearInterval( timerId )` to stop the interval loop.
我建议添加错误处理以在第一个错误时停止间隔循环:
/** @type {number} */
let intervalTimerId = null;
async function getContent() {
try {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
const content = await page.content();
await console.log(content);
await browser.close();
}
catch( err ) {
console.error( "Error in getContent: %o", err );
if( intervalTimerId ) {
window.clearInterval( intervalTimerId );
}
}
}
intervalTimerId = window.setInterval( getContent, 13 * 1000 );
替代方法:
正如@mplungjan 和@RohanAsokan 等其他用户所指出的那样,您的代码存在潜在的设计问题,因为setInterval 将每13 秒调用一次getContent,即使之前对getContent 的调用仍未完成然而 - 如果(例如)await page.content() 运行时间超过 13 秒,就会发生这种情况。
在这种情况下,解决方案是使用window.setTimeout 而不是window.setInterval 并从getContent 中调用它,如下所示:
/** @type {number} */
let lastSetTimeoutId = null;
async function getContentAndStartLoop() {
try {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
const content = await page.content();
console.log(content);
await browser.close();
lastSetTimeoutId = window.setTimeout( getContentAndStartLoop, 13 * 1000 );
}
catch( err ) {
console.error( "Error in getContent: %o", err );
}
}
请注意,getContentAndStartLoop 将在第一个循环后解决,但会继续运行,直到引发错误。
更好的方法:
我认为最好像这样构造它(使用setTimeout 的setTimeout 适配器,名为delay):
async function myProgram() {
const url = "https://thispersondoesnotexist.com/":
const browser = await puppeteer.launch();
const page = await browser.newPage();
try {
while( true ) {
await page.goto( url );
const content = await page.content();
console.log( content );
await delay( 13 * 1000 );
}
}
catch( err ) {
console.error( "Error in myProgram: %o", err );
}
finally {
await browser.close();
}
}
async function delay( ms, state = null ) {
return new Promise( ( resolve, reject ) => {
window.setTimeout( () => resolve( state ), ms );
} );
}