如何使用PhantomJS检测网页的背景颜色

How can I detect the background color of a webpage with PhantomJS?

本文关键字:背景 颜色 网页 检测 何使用 PhantomJS      更新时间:2023-09-26

我使用PhantomJS通过render()函数对一些网页进行光栅化,有时生成的图像会有黑色背景(正如常见问题解答底部所说,这应该是一种正常行为)。

但如果网页没有设置背景颜色,我想只设置白色背景,如下所示:

page.evaluate(function() {
  if (getComputedStyle(document.body, null).backgroundColor === 'transparent') {
    document.body.bgColor = 'white';
  }
});

但它根本不起作用。我也尝试过:

=== 'rgba(0, 0, 0, 0)'

但无济于事。

我在这里错过了什么?

请注意,有些页面可以在根html标记上设置背景色。示例如下:http://helpdesk.symphonical.com/hc/en-us

设置"body"背景颜色将覆盖"html"标记中的颜色。

我最终为根html标签设置了颜色,这样即使body有其他颜色,它也会在page.evaluate:中从html隐藏我们的自定义颜色

// test the top-level HTML tag since it can also contain backgroundColor
// and we don't wont to override it in body
if (getComputedStyle(document.documentElement, null).backgroundColor === 'rgba(0, 0, 0, 0)') {
    console.log('document.documentElement backgroundColor is transparent, setting color to white');
    var style = document.createElement('style'),
    text = document.createTextNode('body { background: #fff }');
    style.setAttribute('type', 'text/css');
    style.appendChild(text);
    document.documentElement.insertBefore(style, document.documentElement.firstChild);
}

您可以添加一个对body具有最低有用特异性(1)的样式元素作为头的第一个元素。引擎将自动使用稍后出现的背景。如果以后没有,就用这个。

page.evaluate(function(){
    var s = document.createElement('style');
    s.setAttribute("type", "text/css");
    s.innerText = "body { background-color: white; }";
    // assuming head exists and is not empty:
    document.head.insertBefore(s, document.head.firstChild);
});

你也可以尝试特异性为0的* { background-color: white; }

我想我发现了问题。实际上:

document.body.bgColor = 'white' 

不起作用。我用的是:

document.body.style.backgroundColor = '#ffffff' 

现在我得到了白色背景。