【问题标题】:Extract multiple tags from within a tag从标签中提取多个标签
【发布时间】:2016-07-21 12:05:49
【问题描述】:

提前感谢您提供的任何帮助。我正在尝试使用 HtmlAgilityPack 抓取一些 HTML,并且在使用 XPATH 语法时遇到了问题。我正在处理的 HTML 有多个标签,我想在 .

中访问所有标签
<p class="row" data-pid="5687754180">
    <a href="/bod/5687754180.html" class="i gallery" data-ids="1:00c0c_fapkFsQg3Dx">
        <span class="price">$5000</span>
    </a>
    <span class="txt">
        <span class="pl">
            <span class="icon icon-star" role="button">
                <span class="screen-reader-text">
                    <? __("favorite this post") ?>
                </span>
            </span>
            <time datetime="2016-07-17 19:36" title="Sun 17 Jul 07:36:03 PM">Jul 17</time> <a href="/bod/5687754180.html" data-id="5687754180" class="hdrlnk">
                <span id="titletextonly">&#9735;&#9735;&#9812;&#9812;&#9812;&#9812;&#9812;1998 Mastercraft Prostar&#12963</span>
            </a>
        </span>
        <span class="l2">
            <span class="price">$5000</span>
            <span class="pnr">
                <span class="px">
                    <span class="p"> pic</span>
                </span>
            </span>
        </span>
        <span class="js-only banish-unbanish">
            <span class="banish">
                <span class="icon icon-trash" role="button"/>
                <span class="screen-reader-text">hide this posting</span>
            </span>
            <span class="unbanish">
                <span class="icon icon-trash red" role="button"/> restore this posting</span>
        </span>
    </span>
</p>

我的想法是我可以遍历所有 标签并在每个标签中获取我需要的标签,但效果并不好。这是我想要得到的:

然后继续下一个

并得到相同的东西。我觉得我快接近了,但我错过了一些重要的东西。例如,这个 sn-p 从每个

中获取我的“data-pid”

,但“titletextonly”一遍又一遍。

感谢您提供的任何帮助!

【问题讨论】:

    标签: c# web-scraping html-agility-pack


    【解决方案1】:

    每当您的 XPath 以 / 开头时,它将始终被视为绝对 XPath(换句话说,相对于根文档)忽略当前上下文元素,在这种情况下由变量 title 引用。也就是说,SelectSingleNode() 将始终返回整个文档中与 XPath 参数匹配的第一个元素,而不考虑上下文元素。

    要使 XPath 相对于上下文元素,您需要在开头添加 .

    var node = title.SelectSingleNode(".//span[@id='titletextonly']");
    

    【讨论】:

    • 就是这样!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    • 1970-01-01
    • 2010-10-17
    • 2013-04-29
    • 2013-07-12
    • 1970-01-01
    • 2016-12-12
    相关资源
    最近更新 更多