Puppeteer Error:Execution context was destroyed, most likely because of a navigation.

Puppeteer Error

Execution context was destroyed, most likely because of a navigation.

代码流程

选择搜索dom
点击跳转
进入页面
输入关键词
进入跳转页面
获取内容

源码

const puppeteer = require('puppeteer');

const getSearch = async () => {
     
    try {
     
        const browser = await puppeteer.launch({
     
            headless: false,
            // args:['--no-sandbox'] // CentOS 下需要
        });
        const page = await browser.newPage();
        await page.goto('http://m.xbiquge.la/modules/article/waps.php', {
      waitUntil: 'networkidle2' });
        const input_search = await page.$('#s_key')
        await input_search.type('斗罗')
        const search_btn = await page.$('.go')
        await search_btn.click();
        let res = await page.evaluate(() => {
     
            let $ = window.$;
            let items = $('.read_book .block');
            let lsArray = [];
            let linkArray = [];
            if (items.length >= 1) {
     
                items.each((index, item) => {
     
                    let ele = $(item);
                    let link = ele.find('.block_img a').attr('href');
                    let image = ele.find('.block_img a img').attr('src');
                    let title = ele.find('.block_txt h2 a').text();
                    // let latestChapter = ele.find('.block_txt p').eq(0).text();
                    // let author = ele.find('.block_txt p').eq(2).text();
                    if ( linkArray.indexOf(link) === -1 ) {
     
                        title = title.replace(/\s*/g,'');
                        // latestChapter = abstract.replace(/\s*/g,'');
                        // author = author.replace(/\s*/g,'');
                        linkArray.push(link);
                        lsArray.push({
     
                            link,
                            title,
                            image,
                            // latestChapter,
                            // author
                        })
                    }
                })
            }
            return lsArray;
        });
        console.log(res)
        await browser.close();  //关闭浏览器
    } catch (e) {
     
        console.log("error:",e.message);
        return false
    }
}
getSearch()
原因

因为页面发生了跳转导致 page 丢失

解决方案

// 在跳转之后添加
await page.waitForNavigation(); // 等待页面跳转


个人结论,如有不对,欢迎纠正;

你可能感兴趣的:(puppeteer,javascript)