【问题标题】:Having trouble displaying the node's content with HtmlAgilityPack使用 HtmlAgilityPack 显示节点内容时遇到问题
【发布时间】:2020-07-26 08:36:03
【问题描述】:

我在对以下网址进行数据抓取时遇到问题:http://patorjk.com/software/taag/#p=display&f=Graffiti&t=Type%20Something%20

问题是:我编写了一个代码,它应该获取某个节点的内容并将其显示在控制台上。但是,节点和特定节点本身的内容似乎无法访问,但我知道它们的存在是因为我在代码中创建了一个条件,以便让我知道是否找到了具有特定主体的节点它确实被找到但由于某种原因没有显示:

private static void getTextArt(string font, string word)
        {
            HtmlWeb web = new HtmlWeb();
            //cureHtml method is just meant to return the http address
            HtmlDocument htmlDoc = web.Load(cureHtml(font, word));
            if(web.Load(cureHtml(font, word)) != null)
                Console.WriteLine("Connection Established");
            else
                Console.WriteLine("Connection Failed!");

            var nodes = htmlDoc.DocumentNode.SelectSingleNode(nodeXpath).ChildNodes;

            foreach(HtmlNode node in nodes)
            {
                if(node != null)
                    Console.WriteLine("Node Found.");
                else
                    Console.WriteLine("Node not found!");

                Console.WriteLine(node.OuterHtml);
            }
        }

        private const string nodeXpath = "//div[@id='maincontent']";
}

网站显示的Html是这样的:

The Html code within the website. Arrows point at the node I'm trying to reach and the content within it I'm trying to display on the console

当我在控制台上运行代码以检查节点及其内容并尝试显示 Xpath 的 OuterHtml 字符串时,控制台将向我显示它的方式:

Console Window Display

我希望你们中的一些人能够向我解释为什么它会这样。我已经在谷歌上尝试了两天的各种搜索,试图找出没有用的问题。提前谢谢大家。

【问题讨论】:

    标签: c# html dom web-scraping html-agility-pack


    【解决方案1】:

    您想要的内容是动态加载的。

    请改用HtmlWeb.LoadFromBrowser() 方法。此外,请检查htmlDoc 以获取null,而不是调用两次。您当前的逻辑并不能保证您的状态。

            HtmlDocument htmlDoc = web.LoadFromBrowser(cureHtml(font, word));
            if (htmlDoc != null)
                Console.WriteLine("Connection Established");
            else
                Console.WriteLine("Connection Failed!");
    

    此外,您还需要对结果进行解码。

                Console.WriteLine(WebUtility.HtmlDecode(node.OuterHtml));
    

    如果这不起作用,那么您的 cureHtml() 方法已损坏,或者您的目标是 .NET Core :)

    【讨论】:

    • 谢谢。但现在我遇到了 LoadFromBrowser 方法的问题。该错误显示为“'HtmlWeb 不包含“LoadFromBrowser”的定义。似乎遇到相同问题的人正在遇到它,因为他们在.NET Core 2.0 上运行,而我在版本:3.1 上运行。 102. 你知道我该如何解决这个问题吗?提前谢谢你。
    • @BrunoMazzei 我懒得问你要针对哪个框架,这是我的错。 LoadFromBrowser 在 HtmlAgilityPack 的 .NET Core 版本中不可用,因为它使用了 WebBrowser 控件,该控件也不是 .NET Core 的一部分,因为它基于 IE。如果这严格来说是一个 Windows 应用程序,而且很简单,而且您很赶时间,那么您可能会考虑切换到“普通”的 .NET Framework。或者,找到一种在 .NET Core 上运行 Ajax 脚本的方法。一个有趣的练习(以及更好的整体解决方案)可能是定位并调用直接生成 ASCII Art 的端点。
    猜你喜欢
    • 1970-01-01
    • 2011-03-07
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多