使用Agility Pack WP8解析HTML页面

时间:2014-04-23 09:33:04

标签: c# html parsing windows-phone-8

我想解析这个文件:(只有重要的部分)

<!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 onload="Xaprb.InputMask.setupElementMasks()">
<div align="center">
        <table> ... </table>
        <table width="900" height="500" border="0" cellpadding="0"
            cellspacing="0" class="content">
        <tr>
    <td width="45">&nbsp;</td>
    <td width="210" valign="top">
    <div class="np_table">
        <div class="np_bl">
            <div class="np_br">
                <div class="np_tl">
                    <div class="np_tr">
                    <span class="name_heading">Hello</span><br />
                    <span class="name_content">**NAME I NEED**</span><br />
                    <br /> <span class="name_heading">Number:</span><br />
                    <span class="name_content">**NUMBER I NEED**</span>
                    </div>
                </div>
            </div>
        </div>
    </div> <br>

    <div class="menu"> ... </div>

    <p>&nbsp;</p>
    </td>
    <td width="600" valign="top">
        <div class="content_table">
        <div class="ct_bl">
            <div class="ct_br">
                <div class="ct_tl">
                    <div class="ct_tr">
                       <span class="heading">...</span>
                       <p><b>**I need this number too: 250**</b> <br />
               <br />
               Here is the datum I want: **17-04-2014**. <br />
               Please do not...</p>
               <p><b>...</b></p>
    <br /><br>
                 </div>
            </div>
        </div>
      </div>
    </div>
    </td>
</body>
</html>

现在我想要四个字符串,两个数字,日期和名字。我有这段代码:

HttpClient client = new HttpClient();
var doc = new HtmlAgilityPack.HtmlDocument();
var html = await client.GetStringAsync("http://example.com");
doc.LoadHtml(html);

var name = ???
var numberone = ???
var numbertwo = ???
var date = ???

但我不知道如何使用HTML Agility Pack成为这些信息。有人能帮助我吗?或者给我提示?

1 个答案:

答案 0 :(得分:0)

我们可以使用XPath查询使用HtmlAgilityPack选择HTML文档的特定部分。因此,请阅读一些XPath教程以开始使用:

例如,要在此问题中从示例HTML中获取NAME I NEED

var name = 
    doc.DocumentNode
       .SelectSingleNode("//span[@class='name_content' and .='Hello']/following-sibling::span[1]");
if(name!= null) Console.WriteLine(name.InnerText);

上述示例中使用的XPath说明:

//span

  • 扫描整个文档以查找<span>元素...

[@class='name_content' and .='Hello']

  • 让类属性值等于"name_content",元素值等于"Hello"

/following-sibling::span[1]

  • 然后从当前<span>获取,最接近<span>类型的兄弟元素......