我正在使用 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() 的理解有误吗?
最佳答案
您将 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()
方法似乎有效的原因是它在两种上下文中都可用,作为 native DOM 方法和 Puppeteer 元素句柄方法。
关于node.js - Puppeteer:Element.hover() 不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63749405/