我正在嘗試使用我從這個實際網站找到的一些代碼來解析一個html doc但是我一直得到一個解析錯誤
HtmlAgilityPack.HtmlDocument htmlDoc = new HtmlAgilityPack.HtmlDocument();
// There are various options, set as needed
htmlDoc.OptionFixNestedTags = true;
// filePath is a path to a file containing the html
htmlDoc.Load(@"C:\Documents and Settings\Mine\My Documents\Random.html");
// Use: htmlDoc.LoadXML(xmlString); to load from a string
// ParseErrors is an ArrayList containing any errors from the Load statement
if (htmlDoc.ParseErrors != null && htmlDoc.ParseErrors.Count > 0)
{
// Handle any parse errors as required
MessageBox.Show("Oh no");
}
else
{
if (htmlDoc.DocumentNode != null)
{
HtmlAgilityPack.HtmlNode bodyNode = htmlDoc.DocumentNode.SelectSingleNode("//head");
if (bodyNode != null)
{
MessageBox.Show("Hello");
}
}
}
任何幫助,將不勝感激 :)
在野外,HTML可能不符合,不符合要求且無法驗證。只有XHTML或非常簡單的HTML才能填充ParseErrors。我注意到HTML Agility Pack非常強大,即使生成了ParseErrors,它仍然可以從大多數HTML源構建一個不錯的DOM樹。刪除else,讓else塊正常執行。
如果它沒有構建DOM樹,那麼您應該調查生成的ParseError。如果它只構建了一個部分樹,請嘗試在節點上進行遞歸,打印或消息框以查看DOM樹的哪些部分已構建。你可能不需要整棵樹。