操纵er的人重新加载页面,直到某些特定样式更改为止

时间:2019-12-14 22:34:22

标签: javascript puppeteer

我想打开Web浏览器并继续重新加载,直到重新加载的页面具有不同的样式,然后再继续执行下一个功能,除非继续重新加载。

假设我有一个P标签,然后重新加载页面,因为display: block

<p id="notYetStarted" style="display: block;">You need to reload the page if u can read me!</p>

但是由于P标签的显示属性现在为display: none;,所以停止重新加载页面(在这种情况下,不是重新加载,而是继续执行其他代码):

<p id="notYetStarted" style="display: none;">You need to reload the page if u can read me!</p>

我尝试使用递归函数,但不起作用:

(async () => {
    try {
//init a browser tab and wait until completely loaded then go to next step
        const browser = await puppeteer.launch({headless:false, args: ['--no-sandbox'] });
        const page = await browser.newPage();
        await page.setViewport({width:1366, height: 768})
        await page.goto(url, { waitUntil: 'networkidle2' });

// wait for Recursive function to be resolve
        await checkPTag(page)
// we are here because p.display:none
// continue execute other codes :)
    }catch(err) {
        console.log(err)
    }
})();

const checkPTag = (page) => {
  return new Promise(async (resolve, reject) => {
//search the dom for p tag and check it's display property
    let result = await isPTagAvailable(page)
    if(result === 'not started') {
      //reload the page cz p.display:block
      await page.reload({ waitUntil: ["networkidle0", "domcontentloaded"] })

//Recursive calling again
        await checkPTag(page)
    }else if(result === 'started') {
//no need reload the page cz p.none
      resolve('started')
    }
  })
}


const isPTagAvailable = (page) => {
  return new Promise (async (resolve, reject) => {
    await page.waitForSelector('#body');

    const pTags = await page.$$eval(
        '#body',
          nodes =>
            nodes.map(element => {
              const p = element.querySelector('p#notYetStarted');
              console.log(p)
            return JSON.parse(JSON.stringify(getComputedStyle(element, null).display));
            } )    
        );
    const pDisplay = pTags[0]

    if(pDisplay === 'block') {
      resolve('not started')
    }else {
      resolve('started')
    } 
  })
}

上面的代码打开一个网络浏览器,等待dom完全加载,并获得display标签的P值,由于它是block,所以到目前为止,重新加载页面还是不错的,但是那么如果显示值更改为none,但仍然尝试重新加载页面。 要求长代码

1 个答案:

答案 0 :(得分:1)

我认为您的代码正在加载与第一个请求相同的缓存。因此,您应该在URL末尾添加一些随机数,以确保响应与第一个响应的缓存不同。

const puppeteer = require ('puppeteer')

const urlPage = 'http://localhost/testing/test_display_none.html'

;(async () => {

    const browser = await puppeteer.launch ({
        headless: false,
        devtools: false
    })

    const [page] = await browser.pages ()

    page.setDefaultNavigationTimeout(0)

    const functionToExecute = async () => {
        // Code to run if P tag display is none (hidden)
        console.log ('P tag display = none\n Executing next defined function...')
    }

    const ifTagPdisplayed = async () => {

        const openPage = await page.goto ( urlPage + '?r=' + Date.now() , { waitUntil: 'networkidle2', timeout: 0 } )

        const elemExist = await page.waitForSelector ('#notYetStarted', { timeout: 0 })

        const getDisplay = await page.evaluate ( () => document.querySelector('#notYetStarted').style.display === 'none' )

        if ( !getDisplay ) {
            await ifTagPdisplayed ()
        } else {
            await functionToExecute ()
        }

    }

    await ifTagPdisplayed ()

})()