繁体   English   中英

HTMLAgilityPack Selectnodes始终返回null

[英]HTMLAgilityPack Selectnodes always returns null

我听说过有关HTMLAgilityPack库的好消息,因此我想尝试一下,但绝对没有成功。 我几个月来一直在努力解决这个问题。 无论我做什么,我都无法获得此代码来给我除null以外的任何东西。 我尝试按照以下示例进行操作( http://www.c-sharpcorner.com/uploadfile/9b86d4/getting-started-with-html-agility-pack/ ),但是我没有得到相同的结果,也无法解释原因。

我尝试加载文件,然后运行SelectNodes选择所有超链接,但它始终返回一个空列表。 我尝试过选择所有类型的节点(div,p,a,所有内容和所有内容),但它始终会返回一个空列表。 我尝试使用doc.Descendants,尝试使用本地和Web上的不同源文件,但我做过的任何事情都不会返回实际结果。

我一定忽略了一些重要的事情,但是我无法弄清楚它是什么。 我可能会缺少什么?

码:

    public string GetSource()
    {
        try
        {
            string result = "";

            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            if (!System.IO.File.Exists("htmldoc.html"))
                throw new Exception("Unable to load doc");

            doc.LoadHtml("htmldoc.html");   // copied locally to bin folder, confirmed it found the file and loaded it

            HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a");  // Always returns null, regardless of what I put in here

            if (nodes != null)  
            {
                foreach (HtmlNode item in nodes)
                {
                    result += item.InnerText;
                }
            }
            else
            {
                // Every. Single. Time.
                throw new Exception("No matching nodes found in document");
            }


            return result;
        }
        catch (Exception ex)
        {                
            return ex.ToString();
        }
    }

我正在使用的源HTML文件'htmldoc.html'如下所示:

<html>  
<head>  
    <title>Testing HTML Agility Pack</title>
</head>  
<body>  
    <div id="div1">  
        <a href="div1-a1">Link 1 inside div1</a>  
        <a href="div1-a2">Link 2 inside div1</a>  
    </div>  
        <a href="a3">Link 3 outside all divs</a>      
        <div id="div2">  
        <a href="div2-a1">Link 1 inside div2</a>  
        <a href="div2-a2">Link 2 inside div2</a>  
    </div>  
</body>  
</html>

要加载文件,应使用Load方法LoadHtml用于包含html的字符串

doc.Load("htmldoc.html"); 

暂无
暂无

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

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