使用HtmlAgilityPack在C#中获取特定数据并将其序列化为json

时间:2016-02-29 06:39:40

标签: c# html json visual-studio html-agility-pack

我已经下载了一个html源代码,我试图从中获取一些数据,将其序列化为“json”文件。

这是html源文件:https://drive.google.com/file/d/0BzweTZsfeoxMTWk2LVdnYTJMRUE/view?usp=sharing

在html代码中有“2”组,我希望从中收集数据。

目前我设法将代码放在这个“2”组中,并使用标签将它显示在两个面板中。我的代码是休闲:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;

namespace Parser_Test_1._0
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.Load(@"C:...\bin\Debug\xbFrSourceCode.txt");

            string datacollected1 = doc.DocumentNode.SelectNodes("//*[@id=\"favoritesContent\"]/div[2]/div[2]/ul")[0].InnerHtml;
            string datacollected2 = doc.DocumentNode.SelectNodes("//*[@id=\"friendsContent\"]/div[2]/div[2]")[0].InnerHtml;
            label1.Text = datacollected1;
            label2.Text = datacollected2;
        }      

    }
}

我希望从这两个组中收集用户和每个用户的相应数据,将其序列化为json文件。

每个用户都以<li ...></li>

分隔

对于我希望得到的每个用户:

  • Gamertag:data-gamertag="this is the gamertag"
  • Gamerpic:它位于class="gamerpicWrapper" src="this is the gamerpic"
  • 真实姓名:<div class="realName">this is the realname</div>
  • PrimaryInfo:<div class="primaryInfo">this is the primaryinfo</div>
  • isOnline:<div class="statusIcon">如果此处有代码,那么在json文件中此值将为true </div>

这是所需“json”文件格式的一个示例(请注意,可能写入的代码很糟糕。):

{
    "favorites" : 
    [
        {
            "gamertag" : "Gamertag1",
            "gamerpic" : "gamerpicURL",
            "realname" : "",
            "primaryInfo" : "",
            "isOnline" : false,
        },
        {
            "gamertag" : "Gamertag2",
            "gamerpic" : "gamerpicURL",
            "realname" : "realname2",
            "primaryInfo" : "primaryinfo2",
            "isOnline" : true,
        },
        {
            "gamertag" : "Gamertag3",
            "gamerpic" : "gamerpicURL",
            "realname" : "",
            "primaryInfo" : "",
            "isOnline" : false,
        },
        {
            "gamertag" : "Gamertag4",
            "gamerpic" : "gamerpicURL",
            "realname" : "realname4",
            "primaryInfo" : "",
            "isOnline" : true,
        }

    ]
    "friends" : 
    [
        {
            "gamertag" : "Gamertag1",
            "gamerpic" : "gamerpicURL",
            "realname" : "",
            "primaryInfo" : "",
            "isOnline" : true,
        },
        {
            "gamertag" : "Gamertag2",
            "gamerpic" : "gamerpicURL",
            "realname" : "realname2",
            "primaryInfo" : "primaryinfo2",
            "isOnline" : false,
        },
        {
            "gamertag" : "Gamertag3",
            "gamerpic" : "gamerpicURL",
            "realname" : "realname3",
            "primaryInfo" : "",
            "isOnline" : true,
        },
        {
            "gamertag" : "Gamertag4",
            "gamerpic" : "gamerpicURL",
            "realname" : "",
            "primaryInfo" : "",
            "isOnline" : false,
        }

    ]
}

如果有人能告诉我如何做到这一点,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

以下代码显示了xpath和HAP的适当用法。 xpath的用法可以简化,但你给了我一个4k的html文件,我不想学习所有这些文件的结构。但是代码会将您想要的所有内容作为变量。现在你的工作是加入json结构 - 但是如果你不了解JSON,那么考虑使用XML。

        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
        doc.OptionFixNestedTags = true;
        doc.Load("damn.html");

        //First off we find the nodes we want to collect data from. Note that we are only looking for a singlenode compared to your code where you find all nodes
        //this could be cut down to selectnodes where we take all <li> tages with each div tag. But for simplicity.
        HtmlNodeCollection favoritesContent = doc.DocumentNode.SelectNodes("//div[@id='favoritesContent']/div[@class='personListWrapper']/div[@class='gamerList']/ul//li");

        foreach (HtmlNode x in favoritesContent)
        {
            //here we find the gamertag which is an attribute in <li> if <li> does not have that value
            //it will then return the deault value ""(empty string as specified)
            string gamerTag = x.GetAttributeValue("data-gamertag", "");
            HtmlNode temp = x.SelectSingleNode("./a[@class='gamerpicWrapper']/*/img[@class='favorite']");
            string srcOnPic = temp.GetAttributeValue("src", "not found");
            string realName = x.SelectSingleNode("./descendant::*//div[@class='realName']").InnerText;
            string primaryInfo = x.SelectSingleNode("./descendant::*//div[@class='primaryInfo']").InnerText;

            if (0 < x.SelectSingleNode("./div[@class='statusIcon']").InnerHtml.Length)
            {
                bool online = true;

            }
        }