【问题标题】:Node is NULL using Xpath and HtmlAgilityPack使用 Xpath 和 HtmlAgilityPack 的节点为 NULL
【发布时间】:2014-07-08 09:08:36
【问题描述】:

我已经为 imdb 网站编写了一个抓取器,现在我需要解析页面。我将使用 HtmlAgilityPack 来实现。

例如,我下载了这个页面: link to IMDb

我已将其保存为 @"D:\IMDb.htm" 在此页面上,我需要指定评论的有用性,例如2062 人中有 1770 人认为以下评论有用:从第一次评论开始。

接下来是我的代码,希望Xpath正确,但是我的Node最后还是NULL(

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using HtmlAgilityPack;


static void Main(string[] args)
{
    var doc = new HtmlDocument();
    doc.LoadHtml("D:\\IMDb.htm");
    Console.WriteLine("res", GetDescription("D:\\IMDb.htm"));
    Console.ReadLine();
}

public static string GetDescription(string html)
{
    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();           
    doc.OptionFixNestedTags = true; 
    doc.Load(new StringReader(html));
    HtmlNode node = doc.DocumentNode.SelectSingleNode("//*[@id='tn15content']/div[1]/small[1]");
    return node.InnerHtml;
}

希望得到您的帮助,因为我不明白出了什么问题..

【问题讨论】:

    标签: c# xpath html-agility-pack xmlnode


    【解决方案1】:

    你不应该在这里使用StringReader,因为html变量包含要加载的HTML文件的路径,而不是它自己的HTML标记:

    HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();           
    doc.OptionFixNestedTags = true; 
    doc.Load(html);
    HtmlNode node = doc.DocumentNode.SelectSingleNode("//*[@id='tn15content']/div[1]/small[1]");
    return node.InnerHtml;
    

    即使html 包含标记,您也可以使用HAP 的内置函数doc.LoadHtml(html)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-21
      • 2011-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      • 2011-04-30
      相关资源
      最近更新 更多