繁体   English   中英

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

[英]Parsing HTML page with HtmlAgilityPack using LINQ

如何在网页上使用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);
    }
}

请尝试以下方法。 您也可以考虑将表拉开,因为它比'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

您必须解析的文档不是最好的解析许多元素缺少类或至少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];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM