无法想象如何使用HTML Agility Pack进行解析

时间:2011-10-14 19:55:55

标签: c# html-parsing html-agility-pack

我有以下大量的HTML代码,但我不知道如何获得指定值

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body >
<form name="form1" method="post" action="" id="form1">
    <div>
    <table class="tableclass" >
       <tbody>
        <tr>        
        <tr>
            <td colspan="5" class="myclass1"><span id="myclass2">value1</span></td>
        </tr>

        <tr id="idvalue" aa="1" class="myclass3a">
            <td><a href="" target="_blank">value2</a></td>
            <td>value3</td>
            <td>value4</td>
            <td>value5</td>
            <td>value6</td>
        </tr>

        <tr id="idvalue" aa="2" class="myclass3b">
            <td><a href="" target="_blank">value2</a></td>
            <td>value3</td>
            <td>value4</td>
            <td>value5</td>
            <td>value6</td>
        </tr>

        <tr id="idvalue" aa="3" class="myclass3c">
            <td><a href="" target="_blank">value2</a></td>
            <td>value3</td>
            <td>value4</td>
            <td>value5</td>
            <td>value6</td>
        </tr>
        </tbody>
        </table>

    </div>

</form>
</body>
</html>

让我分析一下这段代码。

该页面有一个表格,第一行的格式略有不同,我希望提取 value1 ,其余各行都有各种类和不同的id值。从每一行到表格的结尾我想提取 value2 value3 value4 value5

感谢您的时间

2 个答案:

答案 0 :(得分:1)

以下......

var document = new HtmlDocument();
...

var nodes = document.DocumentNode.Descendants("td");
foreach(var node in nodes)
{
    Console.WriteLine(node.InnerText);
}

...可生产

value1
value2
value3
value4
value5
value6
value2
value3
value4
value5
value6
value2
value3
value4
value5
value6

希望这就是你所追求的目标。

答案 1 :(得分:1)

var doc = new HtmlDocument();
doc.Load(url);

var table = doc.DocumentNode.SelectSingleNode("//table[@class='tableclass']");
var value1 = table.Descendants("tr").Skip(1)
    .Select(tr => tr.InnerText.Trim())
    .First();
var theRest =
    from tr in table.Descendants("tr").Skip(2)
    let values = tr.Elements("td")
        .Select(td => td.InnerText.Trim())
        .ToList()
    select new
    {
        Value2 = values[0],
        Value3 = values[1],
        Value4 = values[2],
        Value5 = values[3],
        Value6 = values[4],
    };