首页 > 解决方案 > 使用 htmlagilitypack 遍历 html 元素不起作用

问题描述

我需要一些帮助,因为我无法使用 htmlagilitypack 开发解析器。

我有一个带有一些子 div 的 div,每个子 div 都包含一个指向一侧的链接。例如。

<html>
<head>
    <title>TODO supply a title</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <div id="test">
    <div>some content</div>
    <div class="project-categories" itemprop="occupationalCategory">
        <div class="cat_object"><a class="cat_child" target="_self" href="1.htm">1</a></div>
        <div class="cat_object"><a class="cat_child" target="_self" href="2.htm7">2</a></div>
        <div class="cat_object"><a class="cat_child" target="_self" href="3.htm">3</a></div>          
    </div>
    </div>
</body>

现在我将 XPath 设置为 I like to Iterate through:

foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//*[@id=\"test\"]/div[2]"))
 {
      System.Diagnostics.Debug.WriteLine(node.InnerText);
 }

结果总是相同的,我只得到一个包含 XPath 的整个 innerHtml 的节点。

    <div class="cat_object"><a class="cat_child" target="_self" href="1.htm">1</a></div>
    <div class="cat_object"><a class="cat_child" target="_self" href="2.htm7">2</a></div>
    <div class="cat_object"><a class="cat_child" target="_self" href="3.htm">3</a></div> 

我做了一些搜索,发现了一些有用的例子,例如。 使用 HtmlAgilityPack 选择节点不起作用

但无论我尝试什么 - 问题仍然存在。

您能帮我访问这些项目以在单个节点中获取每个项目吗?

谢谢!安德烈

标签: asp.net

解决方案


我想我明白了。缺少额外的 /div 所以

foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//*[@id=\"test\"]/div[2]/div"))

工作正常。


推荐阅读