木偶:Element.hover()不存在

时间:2020-09-05 00:33:19

标签: node.js puppeteer

我正在使用puppeteer从站点上抓取一些图像以及一些其他数据。要更改图像,我需要将鼠标悬停在列表项上。我一直在.hover()周围遇到文档,但是没有成功。但是,.click()非常适合我的抓取部分。

const pptr = require('puppeteer');

async function scrapeProduct(productID) {
    const browser = await pptr.launch();
    const page = await browser.newPage();
    await page.goto(`https://someplace.com`);
    let scrapeData = await page.evaluate(async () => {
        let productMap = [];

        //scrape other data...

        const imageItems = document.querySelectorAll('ul[class="images-view-list"] > li > div');
        for (let image of imageItems) {
            await image.hover();
            productMap.push({
                'Image Src': document.querySelector('div[class="image-view-magnifier-wrap"] > img').getAttribute('src'),
            });
        }
        return productMap;
    });
    await browser.close();
    return scrapeData;
}

我看到了一些解决方案,您可以在这些解决方案中先执行悬停来评估页面。这很不方便,因为我收集了许多其他数据点,并希望在一个评估请求中保持解决方案的清洁。我对.hover()的理解不正确吗?

1 个答案:

答案 0 :(得分:2)

您正在将Puppeteer函数与在DOM上下文中执行的评估函数混合在一起。如果要使用Puppeteer悬停,则需要使用来自page.$$查询的图像引用:

let productMap = [];
const page = await browser.newPage();
await page.goto(`https://someplace.com`);
//get a collection of Puppeteer element handles
const imageItems = await page.$$('ul[class="images-view-list"] > li > div');
for (let image of imageItems) {
    //hover on each element handle
    await image.hover();
    //use elementHandle getProperty method to get the current src
    productMap.push({'Image Src': await (await image.getProperty('src')).jsonValue()});
}

如果需要在page.evaluate函数中执行此操作,则需要使用正常的DOM鼠标事件来模拟悬停。

click()方法似乎起作用的原因是,它在两种情况下都可以使用,既可以用作本机DOM方法,也可以用作Puppeteer元素句柄方法。