有什么方法可以找到RGB颜色的元素吗? (WebDriver,C#)

时间:2016-11-21 00:33:08

标签: c# selenium-webdriver webdriver

为了让我的程序工作,我需要找到一个特定RGB颜色的独特元素。基本上,我试图看看是否有一种方法可以找到页面上的所有元素,找到具有这种特定RGB颜色的元素并将它们的坐标保存到变量中。

这是可能的,如果是的话,我将如何做到这一点?

示例代码:

    Console.WriteLine("Successfully found question set.");
    Thread.Sleep(3000);
    go:
    try
    {
        if (!rage)
        {
            Random interval = new Random();
            int waitTime = interval.Next(1000, 10000);
            Thread.Sleep(waitTime);
        }
        driver.FindElement(By.Id("btnCheckAnswer")).Click();
        //Insert font finding and coordinate saving here.
        driver.FindElement(By.Id("bNext.Image")).Click();
        goto go;
    } //Omitted the "Catch" section as it is unneccessary here.

HTML示例:http://pastebin.com/Y6Ye6Cqu

谢谢,

MTS11648

1 个答案:

答案 0 :(得分:0)

从您的HTML中,我假设您要检查的所有元素都具有相同的ID。这在技术上违背了HTML标准,但它对我们有利,因为我们只能抓取这些元素,然后检查每个元素,看它是否是正确的颜色。一旦你有了一个元素,就可以使用.GetCssValue("color")获得它的颜色,这将返回这种格式的RGB值,"rgba(180, 137, 59, 1)".你会注意到这是RGBA而不是RGB。您可以阅读有关RGBA here的更多信息。您需要将预期的RGB值转换为RGBA,但这非常简单...... rgb(180, 137, 59)变为rgba(180, 137, 59, 1).

下面的代码将使用指定的ID擦除所有元素,并根据预期的颜色将其过滤为新的List。从那里我们可以遍历filtered集合并使用.Location.[X|Y]写出每个元素的坐标。

// IReadOnlyCollection<IWebElement> unfiltered = Driver.FindElements(By.Id("brdrQuestion.QuestionRenderer.StackPanel.MultiChoiceQuestionViewer.sp.StackPanel.RadioTextRegionViewer1.LayoutRoot.Panel.text.sp.rich.LayoutRoot.TextBlock"));
IReadOnlyCollection<IWebElement> unfiltered = Driver.FindElements(By.CssSelector("*"));
Console.WriteLine(unfiltered.Count);
List<IWebElement> filtered = unfiltered.Where(f => f.GetCssValue("color") == "rgba(180, 137, 59, 1)").ToList();
Console.WriteLine(filtered.Count);
foreach (IWebElement element in filtered)
{
    Console.WriteLine(element.Location.X);
    Console.WriteLine(element.Location.Y);
}