【问题标题】:Using HtmlAgilityPack to get specific data in C# and serialize it to json使用 HtmlAgilityPack 获取 C# 中的特定数据并将其序列化为 json
【发布时间】:2016-06-12 03:03:00
【问题描述】:

我已经下载了一个 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>分隔

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

  • 玩家代号:data-gamertag="this is the gamertag"
  • Gamerpic:在class="gamerpicWrapper"src="this is the gamerpic"
  • 实名:<div class="realName">this is the realname</div>
  • 主要信息:<div class="primaryInfo">this is the primaryinfo</div>
  • isOnline:<div class="statusIcon">如果这里有代码,那么在json文件中这个值为真</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,
        }

    ]
}

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

【问题讨论】:

  • 感谢您的建设性批评。我一生中的大部分时间都被编码所吸引,但最近我决定深入尝试它。我决定从学习 C# 开始。为了学习这门语言,我决定从事一个项目并学习试图创建和完成这个项目的语言。在我发布这个问题的那一刻,我正在开始这个项目。我已经想出了如何做我在这个问题中所要求的。并回答你的问题,是的。最初我从 chrome 获得了 xpaths。虽然我不知道如何手动表达和编写 xpath,但我现在知道了。
  • 好吧。您需要知道 xpath 才能继续。这次我会帮你的。看看this,我会为你生成一些代码。
  • 记得标记正确答案,如果对您有帮助,请至少评论一下。

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


【解决方案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;

            }
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-23
    • 1970-01-01
    • 2020-11-24
    • 2011-02-02
    • 2014-08-17
    • 2021-11-08
    相关资源
    最近更新 更多