【发布时间】:2018-08-10 17:06:54
【问题描述】:
所以当我尝试使用 Html Agility Pack 解析 HTML 文档时。我加载了 html 文档,它可以工作。问题出在我尝试使用 XPath 解析它时。我收到“System.NullReferenceException:'对象引用未设置为对象的实例。'”错误。
要获取我的 xpath,我使用 Chrome 开发窗口并突出显示包含我要解析的数据的行的整个表,右键单击它并复制 Xpath。
这是我的代码
string url = "https://www.ctbiglist.com/index.asp";
string myPara = "LastName=Smith&FirstName=James&PropertyID=&Submit=Search+Properties";
string htmlResult;
// Get the raw HTML from the website
using (WebClient client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
// Send in the link along with the FirstName, LastName, and Submit POST request
htmlResult = client.UploadString(url, myPara);
//Console.WriteLine(htmlResult);
}
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(htmlResult);
HtmlNodeCollection table = doc.DocumentNode.SelectNodes("//*[@id=\"Table2\"]/tbody/tr[2]/td/table/tbody/tr/td/div[2]/table/tbody/tr[2]/td/table/tbody/tr[2]/td/form/div/table[1]/tbody/tr");
Console.WriteLine(table.Count);
当我运行此代码时,它可以工作,但会抓取 HTML 文档中的所有表格。
var query = from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
from row in table.SelectNodes("//tr").Cast<HtmlNode>()
from cell in row.SelectNodes("//th|td").Cast<HtmlNode>()
select new { Table = table.Id, CellText = cell.InnerText };
foreach (var cell in query)
{
Console.WriteLine("{0}: {1}", cell.Table, cell.CellText);
}
我想要的是一个特定的表,它包含所有表行,其中包含我要解析为对象的数据。
谢谢你的帮助!!!
【问题讨论】:
-
代码中有很多地方会出现该错误。错误发生在哪一行?
-
HtmlNodeCollection table = doc.Docu.... "Console.WriteLine(table.Count);" 之前的行
标签: c# parsing xpath html-agility-pack nullreferenceexception