Can't figure how to parse using HTML Agility Pack

让人想犯罪 __ 提交于 2019-12-11 08:02:36

问题


I have the following chunk of HTML code but i cant figure how i can get the designated values

    <!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>

Let me analyze a little this code.

The page has a table with the 1st row having a slightly different format where i want to extract the value1 and the rest of the rows that each have an a variety of classes and different id values and from each row until the end of the table i want to extract value2, value3, value4, value5

Thanks for your time


回答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],
    };



回答2:


The following...

var document = new HtmlDocument();
...

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

Produces...

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

Hopefully that is what you are after.



来源:https://stackoverflow.com/questions/7772872/cant-figure-how-to-parse-using-html-agility-pack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!