C#如何获得div类的跨度?

时间:2016-12-24 10:58:54

标签: c# html parsing

我想创建一个应用程序,用于搜索特定关键字并显示关键字的定义。我正在使用网页浏览器,它正在浏览网站。现在我想解析该HTML代码并获取带有描述的<span>。那可能吗?我无法解决这个问题。

以下是HTML代码:

<div class="_G1d _wle _xle">
    <div class="_RBg">
        <div class="mod" data-md="50" style="clear:none" data-ved="0ahUKEwjL6Nn40YzRAhWBeFAKHW6qAOwQkCkIrQEoATAV">
            <!--m-->
            <div class="_cgc" data-hveid="174" data-ved="0ahUKEwjL6Nn40YzRAhWBeFAKHW6qAOwQziAIrgEoADAV">
                <div jsl="$t t-oF0h478wPRI;$x 0;" class="r-iv2Iqojxo_88">
                    <div class="kno-rdesc r-ia8pb7p3eFsA" jsl="$t t-JgTEvN6zUII;$x 0;">
                    <span>
                        "The Eiffel Tower is a wrought iron lattice tower on the Champ de Mars in Paris, France. It is named after the engineer Gustave Eiffel, whose company designed and built the tower."
                    </span>
                    <span>...</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <!--n-->
</div>

那是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    webBrowser1.Navigate("https://www.google.de/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=" + textBox1.Text);
    Get_Data();
}

private void Get_Data()
{
    foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div"))
        if (el.GetAttribute("className") == "_cgc")
        {
            description.Text = el.InnerText;
        }
}

1 个答案:

答案 0 :(得分:0)

也许您可以使用Split来获取范围:

    private void Get_Data()
    {
        foreach (HtmlElement el in webBrowser1.Document.GetElementsByTagName("div"))
        {
            if (el.GetAttribute("className") == "_cgc")
            {
                string[] splitSpan = el.InnerText.Split(new[] { "<span>", "</span>" }, StringSplitOptions.None);
                description.Text = splitSpan[1];
            }
        }
    }