我有asp.net mvc应用程序和html页面,我使用HtmlAgilityPack进行解析,但是当我尝试循环元素时,我的预测中有下一个错误:Object reference not set to an instance of an object。下一个是我的密码。有人知道我的错误在哪里吗?我刚开始使用htmlagilitypack。
的一部分:
<li class="b-serp-item i-bem" onclick="return {"b-serp-item":{}}">
<i class="b-serp-item__favicon" style="background-position: 0 -0px"></i>
<h2 class="b-serp-item__title">
<b class="b-serp-item__number">1</b>
<a class="b-serp-item__title-link" href="http://googlescraping.com/google-scraper.php">Google</a>
</h2>
</li>码
DateTime dt = DateTime.Now;
string dtf = String.Format("{0:u}", dt);
string wp = "page" + dtf + ".html";
HtmlDocument HD = new HtmlDocument();
HD.Load(wp);
string output = "";
foreach (HtmlNode node in HD.DocumentNode.SelectNodes("//a[@class='b-serp-item__title-link']"))
{
output += node.GetAttributeValue("href", null) + " ";
}我在google驱动器中共享了Html输出:https://drive.google.com/file/d/0B3-m-r5Ce0gOSTlzUGlTT1VBb00/edit?usp=sharing
发布于 2014-02-06 21:11:03
我运行您的代码时只做了一个小小的更改,我使用了HtmlDocument.LoadHtml(stringContents)而不是HtmlDocument.Load(path),然后它运行得完美无缺。
我怀疑代码无法从路径中找到文件。使用File.Exists(wp)确保文件存在,并考虑使用完全限定的路径,而不是仅使用文件名,使用wp = Path.GetFullPath(wp)。
或者首先使用string contents = File.ReadAllText(wp);读取内容以获取内容,然后在HtmlDocument上使用LoadHtml方法。
https://stackoverflow.com/questions/21598418
复制相似问题