如何选择 CSS 中定义的图像名称?
我可以使用 JavaScript 选择 CSS 图像类,但如何获取该类中的图像名称?我想在 Puppeteer/Node.js 中执行此操作。
如果下面给出的类中的图像与 paper.gif
匹配,我想单击下面给出的此类。
类别:
.height-20 span a {
background-image: url("paper.gif");
background-color: #cccccc;
}
选择器:
let elements = document.querySelectorAll('.height-20 span a'); // Select all Products but how to get image inside this selector?
点击器:
await page.click(".height-20 span a");
我想要实现的目标如下:
if(css image == paper.gif) {
await page.click(".height-20 span a");
}
最佳答案
您可以将 NodeList
转换为获取自document.querySelectorAll()
到 Node 数组,然后您可以按包含 background-image
的元素过滤该数组等于'paper.gif'
:
const elements = [...document.querySelectorAll('.height-20 span a')].filter(e => {
const background_image = window.getComputedStyle(e).backgroundImage.split('/').pop().replace(/[")]/g, '');
return background_image === 'paper.gif';
});
这个实现可以放在 page.evaluate()
里面,你可以click()
如果存在与给定条件匹配的元素,则返回该页面 DOM 范围内的元素:
await page.evaluate(() => {
const elements = [...document.querySelectorAll('.height-20 span a')].filter(e => {
const background_image = window.getComputedStyle(e).backgroundImage.split('/').pop().replace(/[")]/g, '');
return background_image === 'paper.gif';
});
if (elements.length) {
elements[0].click();
}
});
关于javascript - 如何选择 CSS Puppeteer/Node.js 中定义的图像名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53205334/