使用WebBrowser读取HTML类

时间:2016-01-12 12:44:37

标签: c# asp.net browser

enter image description here

<div class="countdownHolder"> <span class="countMinutes"> <span class="position"> <span class="digit static" style="top: 0px; opacity: 1; transition: 350ms ease;">0</span> </span> <span class="position"> <span class="digit static" style="top: 0px; opacity: 1; transition: 350ms ease;">0</span> </span> </span> <span class="countDiv countDiv0">:</span> <span class="countSeconds"> <span class="position"> <span class="digit static" style="top: 0px; opacity: 1; transition: 350ms ease;">4</span> </span> <span class="position"> <span class="digit static" style="top: 0px; opacity: 1; transition: 350ms ease;">0</span> </span> </span> </div>

我试图读取此图片中突出显示的值,不太确定如何从我所在的位置获取它。

功能

private HtmlElement[] GetElementsByClassName(WebBrowser wb, string tagName, string className)
{
    var l = new System.Collections.Generic.List<HtmlElement>();

    if (wb != null && wb.Document != null)
    {
        var els = wb.Document.GetElementsByTagName(tagName);
        foreach (HtmlElement el in els)
        {
            if (el.GetAttribute("className") == className)
            {
                l.Add(el);
            }
        }
    }

    return l.ToArray();
}

我怎么称呼它,似乎找到了countdownHolder类

var countdownHolder = GetElementsByClassName(_webBrowser, "div", "countdownHolder");
if (countdownHolder.Length != 0)
{

}

1 个答案:

答案 0 :(得分:1)

我不知道答案,但我会建议一个策略:

var countdownHolder = GetElementsByClassName(_webBrowser, "div", "countdownHolder");
foreach (var element in countdownHolder.ToList())
{
    //  inspect element here
}

GetElementsByClassName有效。

更新:

以下内容应该可以满足您的需求。

foreach (var element in countdownHolder)
{
    var item1 = element.InnerText; //or
    var item2 = element.OuterText; //both give the same answer here
    // do something
}

通常,请查看element

的属性

更新2:

实际结构是:

<div class='countdownHolder'> 
    <span class='countMinutes'> 
        <span class='position'> 
            <span class='digit static' style='top: 0px; opacity: 1; transition: 350ms ease;'>
                0
            </span> 
        </span> 
        <span class='position'> 
            <span class='digit static' style='top: 0px; opacity: 1; transition: 350ms ease;'>
            0
            </span> 
        </span> 
    </span> 
    <span class='countDiv countDiv0'>
        :
    </span> 
    <span class='countSeconds'> 
        <span class='position'> 
            <span class='digit static' style='top: 0px; opacity: 1; transition: 350ms ease;'>
                4
            </span> 
        </span> 
        <span class='position'> 
            <span class='digit static' style='top: 0px; opacity: 1; transition: 350ms ease;'>
                0
            </span> 
        </span> 
    </span> 
</div>

嵌入的文本以:为分隔符给出分钟和秒。在此示例中00:40。使用额外的空格:0 0 : 4 0

现在你需要的只是简单的字符串处理。您可以通过多种方式执行此操作。 string time = element.InnerText.Replace(" ", "");将删除空格。然后有许多不同的方法来处理min:sec结构