我想将我的 Asics 运行计划导出到 iCal,但由于 Asics 不提供此服务,我决定构建一个小的 scraper 供我个人使用。我想要做的是从我的计划中获取所有计划的运行并基于它生成一个 iCal 提要。我正在使用 C# 和 Html Agility Pack。
我想做的是遍历我所有的计划运行(它们是 div 节点)。然后接下来我想用我的运行节点选择几个不同的节点。我的代码如下所示:
foreach (var run in doc.DocumentNode.SelectSingleNode("//div[@id='scheduleTable']").SelectNodes("//div[@class='pTdBox']"))
{
number++;
string date = run.SelectSingleNode("//div[@class='date']").InnerText;
string type = run.SelectSingleNode("//span[@class='menu']").InnerHtml;
string distance = run.SelectSingleNode("//span[@class='distance']").InnerHtml;
string description = run.SelectSingleNode("//div[@class='description']").InnerHtml;
ViewData["result"] += "Dato: " + date + "<br />";
ViewData["result"] += "Tyep: " + type + "<br />";
ViewData["result"] += "Distance: " + distance + "<br />";
ViewData["result"] += "Description: " + description + "<br />";
ViewData["result"] += run.InnerHtml.Replace("<", "<").Replace(">", ">") + "<br />" + "<br />" + "<br />";
}
我的问题是run.SelectSingleNode("//div[@class='date']").InnerText
不在给定运行节点中选择具有给定 XPath 的节点。它选择整个文档中与 XPath 匹配的第一个节点。
如何在当前节点中选择具有给定 XPath 的单个节点?
谢谢。
更新
我尝试将我的 XPath 字符串更新为:
string date = run.SelectSingleNode(".div[@class='date']").InnerText;
这应该选择 <div class="date"></div>
当前节点内的元素,对吧?好吧,我试过了,但出现了这个错误:
Expression must evaluate to a node-set. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Xml.XPath.XPathException: Expression must evaluate to a node-set.
有什么建议吗?
最佳答案
一些在使用 HtmlAgilityPack 和 XPath 表达式时对您有帮助的事情。
如果run
是一个 HtmlNode
,然后:
run.SelectNodes("//div[@class='date']")
Will 的行为与doc.DocumentNode.SelectNodes("//div[@class='date']")
完全一样。run.SelectNodes("./div[@class='date']")
都给你<div>
run
的子节点节点。它不会搜索得更深,只会在下一个深度级别搜索。run.SelectNodes(".//div[@class='date']")
将返回所有<div>
具有该类属性的节点,但不仅在run
旁边节点,但也会深入搜索(它的每个可能的后代)
您必须在 2. 或 3. 之间做出选择,具体取决于哪一个满足您的需求:)
关于c# - Html Agility Pack - 选择子节点时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6181014/