[英]How to reload page in Puppeteer?
每當頁面加載不正確或遇到問題時,我都希望重新加載頁面。 我嘗試了page.reload()
但是它不起作用。
for(const sect of sections ){
// Now collect all the URLs
const appUrls = await page.$$eval('div.main > ul.app-list > li > div.app-info a.app-info-icon', links => links.map(link => link.href));
// Visit each URL one by one and collect the data
for (let appUrl of appUrls) {
var count = i++;
try{
await page.goto(appUrl);
const appName = await page.$eval('div.det-name-int', div => div.innerText.trim());
console.log('\n' + count);
console.log(appName);
} catch(e){
console.log('\n' + count);
console.log('ERROR', e);
await page.reload();
}
}
}
它給了我這個錯誤:
ERROR Error: Error: failed to find element matching selector "div.det-name-int"
at ElementHandle.$eval (C:\Users\Administrator\node_modules\puppeteer\lib\JS
Handle.js:418:13)
at process._tickCallback (internal/process/next_tick.js:68:7)
-- ASYNC --
at ElementHandle.<anonymous> (C:\Users\Administrator\node_modules\puppeteer\
lib\helper.js:108:27)
at DOMWorld.$eval (C:\Users\Administrator\node_modules\puppeteer\lib\DOMWorl
d.js:149:21)
at process._tickCallback (internal/process/next_tick.js:68:7)
-- ASYNC --
at Frame.<anonymous> (C:\Users\Administrator\node_modules\puppeteer\lib\help
er.js:108:27)
at Page.$eval (C:\Users\Administrator\node_modules\puppeteer\lib\Page.js:329
:29)
at Page.<anonymous> (C:\Users\Administrator\node_modules\puppeteer\lib\helpe
r.js:109:23)
at main (C:\Users\Administrator\Desktop\webscrape\text.js:35:43)
at process._tickCallback (internal/process/next_tick.js:68:7)
某些鏈接無法成功加載。 當我手動刷新這些頁面時,它可以工作。 因此,我希望有一個函數或方法可以幫助我在出現錯誤時自動重新加載頁面。
我設法使用while循環解決它。
for (let appUrl of appUrls) {
var count = i++;
while(true){
try{
await page.goto(appUrl);
const appName = await page.$eval('div.det-name-int', div => div.innerText.trim());
console.log('\n' + count);
console.log('Name: ' , appName);
break;
} catch(e){
console.log('\n' + count);
console.log('ERROR');
await page.reload(appUrl);
continue;
}
}
這對我有用:
await page.reload({ waitUntil: ["networkidle0", "domcontentloaded"] });
有關詳細信息,請參見Puppeteer文檔: https : //github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagereloadoptions
因此,在注釋之后,以下行將導致錯誤。
ERROR Error: Error: failed to find element matching selector "div.det-name-int"
因為Puppetteer具有瀏覽器回調。 當找到該元素並調用回調時,如果該元素不存在,則會引發錯誤。
另外,頁面也被重新加載。 之后,您什么也沒做。 如果要在此之后獲取圖像。 采用
await page.$eval('div.det-name-int', div => div.innerText.trim());
重新加載后。 或者,您可以使用while循環來連續檢查元素是否存在。 如果沒有,請刷新頁面並再次檢查。 這樣可以確保您始終擁有內容。
但是,如果您的內容是動態生成的,並且在您閱讀頁面時卻不是DOM的一部分,那么您的代碼將變得毫無用處。 您可能需要添加超時,然后在dom中搜索該元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.