我一直在尝试使用Puppeteer来检测网页上是否存在黄色。任何关于如何实现这一点的见解都将不胜感激!
发布于 2020-11-15 07:58:50
使用getComputedStyle
您可以通过在页面的所有元素上应用getComputedStyle来获取页面的颜色:
let colr = new Set();
document.body.querySelectorAll('*').forEach(n => {
colr.add(window.getComputedStyle(n).color);
colr.add(window.getComputedStyle(n).backgroundColor);
});
colr = [...colr];或者在这个页面上使用Puppeteer:
// from-dom.js
const puppeteer = require('puppeteer-core');
module.exports = async () => {
// I'm running Puppeteer against Chrome in Docker. Change where necessary please.
const browser = await puppeteer.connect({ browserWSEndpoint: 'ws://localhost:3000' });
const page = await browser.newPage();
await page.goto('https://stackoverflow.com/q/64839035/1244884');
const colors = await page.evaluate(() => {
let colr = new Set();
document.body.querySelectorAll('*').forEach(n => {
colr.add(window.getComputedStyle(n).color);
colr.add(window.getComputedStyle(n).backgroundColor);
});
colr = [...colr];
return colr;
});
await browser.close();
console.log(colors);
};node -p -e 'require("./from-dom.js")()'它返回:
[
'rgb(36, 39, 41)', 'rgba(0, 0, 0, 0)',
'rgb(250, 250, 251)', 'rgb(0, 119, 204)',
'rgb(132, 141, 149)', 'rgb(60, 65, 70)',
'rgb(255, 255, 255)', 'rgb(83, 90, 96)',
'rgb(12, 13, 14)', 'rgb(106, 115, 124)',
'rgb(214, 217, 220)', 'rgb(187, 192, 196)',
'rgb(244, 128, 36)', 'rgb(57, 115, 157)',
'rgb(225, 236, 244)', 'rgb(0, 149, 255)',
'rgb(239, 240, 241)', 'rgb(244, 248, 251)',
'rgb(59, 64, 69)', 'rgb(27, 64, 114)',
'rgb(209, 229, 241)', 'rgb(228, 230, 232)',
'rgb(0, 0, 0)', 'rgb(253, 247, 227)',
'rgb(61, 143, 88)', 'rgb(209, 56, 61)',
'rgb(57, 86, 151)', 'rgb(239, 239, 239)',
'rgb(192, 45, 46)', 'rgb(192, 72, 72)',
'rgb(251, 242, 212)', 'rgb(94, 186, 125)',
'rgba(12, 13, 14, 0.5)'
]

带有屏幕截图
在这里,让我们再次截图这个页面:
// from-picture.js
const puppeteer = require('puppeteer-core');
const path = require('path');
const getColors = require('get-image-colors');
module.exports = async () => {
// I'm running Puppeteer against Chrome in Docker. Change where necessary please.
const browser = await puppeteer.connect({ browserWSEndpoint: 'ws://localhost:3000' });
const page = await browser.newPage();
await page.goto('https://stackoverflow.com/q/64839035/1244884');
await page.screenshot({path: 'screenshot.png'});
await browser.close();
const options = {count: 10, type: 'image/png'};
const colors = await getColors(path.join(__dirname, 'screenshot.png'), options);
console.log(colors.map(c => c.css()));
};node -p -e 'require("./from-picture.js")()'它返回:
[
'rgb(55,76,87)',
'rgb(250,250,251)',
'rgb(150,161,169)',
'rgb(242,133,38)',
'rgb(92,176,224)',
'rgb(203,214,223)',
'rgb(157,90,31)',
'rgb(226,204,156)',
'rgb(244,180,132)'
]

下面是调色板:

你如何辨别一种颜色是否略带黄色?
这一点很棘手。如何判断rgb(61, 143, 88)是否为±黄色?
像chroma-js这样的库应该可以检查颜色是否“在黄色范围内”,但我不知道如何做到这一点。
我找到了这个老帖子,可能会有帮助:Find closest colour match within range of colours
希望这足以让您入门;)
https://stackoverflow.com/questions/64839035
复制相似问题