使用LINQ解析带有HtmlAgilityPack的HTML页面

时间:2013-12-31 06:17:29

标签: c# linq html-agility-pack

如何在网页上使用Linq解析html并将值添加到字符串中。我正在使用Metro应用程序上的HtmlAgilityPack,并希望带回3个值并将它们添加到字符串中。

这是url = http://explorer.litecoin.net/address/Li7x5UZqWUy7o1tEC2x5o6cNsn2bmDxA2N

我想从下面的内容中看到“belwo”

“余额:”, “交易”, “已接收”

WebResponse x = await req.GetResponseAsync();
HttpWebResponse res = (HttpWebResponse)x;
if (res != null)
{
    if (res.StatusCode == HttpStatusCode.OK)
    {
        Stream stream = res.GetResponseStream();
        using (StreamReader reader = new StreamReader(stream))
        {
            html = reader.ReadToEnd();
        }
        HtmlDocument htmlDocument = new HtmlDocument();
        htmlDocument.LoadHtml(html);

        string appName = htmlDocument.DocumentNode.Descendants // not sure what t
        string a = "Name: " + WebUtility.HtmlDecode(appName);
    }
}

2 个答案:

答案 0 :(得分:2)

请尝试以下方法。您也可以考虑将桌子拉开,因为它比“p”标签中的自由文本形成得更好。

干杯,亚伦。

// download the site content and create a new html document
// NOTE: make this asynchronous etc when considering IO performance
var url = "http://explorer.litecoin.net/address/Li7x5UZqWUy7o1tEC2x5o6cNsn2bmDxA2N";
var data = new WebClient().DownloadString(url);
var doc = new HtmlDocument();
doc.LoadHtml(data);

// extract the transactions 'h3' title, the node we want is directly before it
var transTitle = 
    (from h3 in doc.DocumentNode.Descendants("h3")
     where h3.InnerText.ToLower() == "transactions"
     select h3).FirstOrDefault();

// tokenise the summary, one line per 'br' element, split each line by the ':' symbol
var summary = transTitle.PreviousSibling.PreviousSibling;
var tokens = 
    (from row in summary.InnerHtml.Replace("<br>", "|").Split('|')
     where !string.IsNullOrEmpty(row.Trim())
     let line = row.Trim().Split(':')
     where line.Length == 2
     select new { name = line[0].Trim(), value = line[1].Trim() });

// using linqpad to debug, the dump command drops the currect variable to the output
tokens.Dump();

'转储()'是一个LinqPad命令,它将变量转储到控制台,以下是转储命令输出的示例:

  • 余额:5 LTC
  • 交易:2
  • 收到:5 LTC
  • 交易时间:0
  • 已发送:0 LTC

答案 1 :(得分:1)

你必须解析的文件不是最好的解析许多元素缺少类或至少id属性但你想得到的是第二个p标签 内容

你可以试试这个

HtmlDocument htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);



var pNodes = htmlDocument.DocumentNode.SelectNodes("//p")
[1].InnerHtml.ToString().Split(new string[] { "<br />" }, StringSplitOptions.None).Take(3);

 string vl="Balance:"+pNodes[0].Split(':')[1]+"Transactions in"+pNodes[1].Split(':')[1]+"Received"+pNodes[2].Split(':')[1];