【问题标题】:Get color attribute from the styles table从样式表中获取颜色属性
【发布时间】:2011-11-15 10:43:25
【问题描述】:

我需要验证 div 的背景颜色值。这是 HTML:

<div id="outercontainer" align="left">

关于背景颜色的信息在文件 style.css 中定义如下:

#outercontainer {
    background-color: #EAEAEA;
    margin-left: auto;
    margin-right: auto;
    opacity: 1;
    width: 1000px;
    z-index: 2;
}

我尝试使用selenium.getattribute 命令获取 bgcolor 的值,但 selenium 向我返回了以下错误消息:

错误:找不到元素属性:css=#oute rcontainer@background-color 会话 bc60eb07f15e4e63986634fb59bf58a1

结果。 我的这部分代码:

try
{
     string atr_str = selenium.GetAttribute("css=#outercontainer@background-color");
     Console.WriteLine(atr_str);
}
catch (SeleniumException)
{
     Console.WriteLine("Color value was not got.");
}

事实上,我用不同类型的定位器尝试了不同的方法,但没有任何帮助。 你有什么建议?

【问题讨论】:

  • 您不能使用 CSS 定位器来访问元素的样式属性。
  • 但是你能告诉我正确的方法吗?我是 Web 开发 QA 方面的新手

标签: css selenium getattribute


【解决方案1】:

我没有 C# 环境来测试它,但这样的东西应该可以工作:

string js = "
    window.document.defaultView.getComputedStyle(
        window.document.getElementById('outercontainer'), null).
            getPropertyValue('background-color');
            ";
string res = selenium.GetEval(js);

现在res 将包含背景颜色的rgba 值。您必须使用 Javascript,因为 Selenium 不适用于计算样式,只能用于 HTML 标记本身中定义的样式。

为了保持可读性,我稍微使用了换行符:js 字符串都可以放在一行上。

【讨论】:

  • 谢谢。我用过这种方式。有用。顺便说一句,它解决了一些其他问题,我已经开始工作了。
  • +1 导致 OP 没有选择您的答案,这是正确的答案
  • 我将背景颜色设为 #730606 。我得到的结果是 res="rgb(115, 6, 6)"。如何比较这两个值?这样我们就可以验证给定的颜色是否正确?
  • 附带说明,这不适用于 IE6、7、8。 Here's how to overcome it.。关于颜色比较 - 你的原件是十六进制的,你的新的是普通十进制,所以你会希望第一个也转换为十进制(或相反 - 你的选择)。
  • 我正在使用 firefox 12。如何将颜色从十六进制转换为 rgd?我可以从here 获取 rgd 值,我可以手动使用它。但是他们有什么方法可以自动转换颜色吗?在硒中......
【解决方案2】:

尝试:

string rgbaColor = yourElement.GetCssValue("background-color");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 2015-07-20
    • 1970-01-01
    • 2011-11-02
    相关资源
    最近更新 更多