Puppeteer:Element.hover() 不存在

Mak*_*ros 2 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Tom*_*Tom 5

您将 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()});
}
Run Code Online (Sandbox Code Playgroud)

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

click()方法似乎有效的原因是它在两种上下文中都可用,作为本机 DOM 方法和 Puppeteer 元素句柄方法。