Puppeteer in NodeJS reports 'Error: Node is either not visible or not an HTMLElement'

后端 未结 4 2252
执笔经年
执笔经年 2021-02-18 18:05

I\'m using \'puppeteer\' for NodeJS to test a specific website. It seems to work fine in most case, but some places it reports:

Error: Node is either not

4条回答
  •  心在旅途
    2021-02-18 18:41

    My way

    async function getVisibleHandle(selector, page) {
    
        const elements = await page.$$(selector);
    
        let hasVisibleElement = false,
            visibleElement = '';
    
        if (!elements.length) {
            return [hasVisibleElement, visibleElement];
        }
    
        let i = 0;
        for (let element of elements) {
            const isVisibleHandle = await page.evaluateHandle((e) => {
                const style = window.getComputedStyle(e);
                return (style && style.display !== 'none' &&
                    style.visibility !== 'hidden' && style.opacity !== '0');
            }, element);
            var visible = await isVisibleHandle.jsonValue();
            const box = await element.boxModel();
            if (visible && box) {
                hasVisibleElement = true;
                visibleElement = elements[i];
                break;
            }
            i++;
        }
    
        return [hasVisibleElement, visibleElement];
    }
    

    Usage

    let selector = "a[href='https://example.com/']";
    
    let visibleHandle = await getVisibleHandle(selector, page);
    
    if (visibleHandle[1]) {
    
       await Promise.all([
         visibleHandle[1].click(),
         page.waitForNavigation()
       ]);
    }
    

提交回复
热议问题