C# Html敏捷包Xpath不工作
所以,当我尝试使用HTML Agility Pack解析HTML文档时。我加载html文档,它就工作了。问题在于我试图使用XPath解析它。我得到一个“System.NullReferenceException:'对象引用未设置为对象的实例'”错误 要获取xpath,我使用Chrome开发窗口,突出显示包含要解析的数据行的整个表,右键单击它并复制xpath 这是我的密码C# Html敏捷包Xpath不工作,c#,parsing,xpath,html-agility-pack,nullreferenceexception,C#,Parsing,Xpath,Html Agility Pack,Nullreferenceexception,所以,当我尝试使用HTML Agility Pack解析HTML文档时。我加载html文档,它就工作了。问题在于我试图使用XPath解析它。我得到一个“System.NullReferenceException:'对象引用未设置为对象的实例'”错误 要获取xpath,我使用Chrome开发窗口,突出显示包含要解析的数据行的整个表,右键单击它并复制xpath 这是我的密码 string url = "https://www.ctbiglist.com/index.asp"; str
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);
}
var query=来自doc.DocumentNode.SelectNodes(“//表”).Cast()中的表
从表中的行选择节点(“//tr”).Cast()
从第行的单元格中选择节点(//th | td”).Cast()
选择新{Table=Table.Id,CellText=cell.InnerText};
foreach(查询中的变量单元格)
{
WriteLine(“{0}:{1}”,cell.Table,cell.CellText);
}
我想要的是一个特定的表,其中包含所有表行,这些表行包含我要解析为对象的数据
谢谢你的帮助 换行
from table in doc.DocumentNode.SelectNodes("//table").Cast<HtmlNode>()
来自doc.DocumentNode.SelectNodes(//table”).Cast()中的表
到
doc.DocumentNode.SelectNodes(“//table[@id=\“Table2\”])中的表中的
。代码中有许多地方可能会出现该错误。错误发生在哪一行?HtmlNodeCollection table=doc.Docu。。。。“Console.WriteLine(table.Count);”前面的行好吧,那么如果我想将它存储在var表中,为什么它会给我同样的错误。可能您的html没有Id为Table2
的表。当我在调试模式下运行它时,我可以看到它,当我只选择整个文档时,它会显示表。
from table in doc.DocumentNode.SelectNodes("//table[@id=\"Table2\"]").Cast<HtmlNode()