【问题标题】:Get all consecutive DIVs with specific class获取具有特定类的所有连续 DIV
【发布时间】:2016-06-10 08:17:51
【问题描述】:

有HTML之类的

<h3>Specifications</h3>
<div class="row"> some text </div>
<div class="row"> some text 2 </div>
<div class="row"> some text 3 </div>
<div class="detail-anchor" id="pricing"></div>
<div class="row"> some text 4</div>

我正在使用 PHP + phpQuery 来抓取网站

我只想获得前 3 个 div,换句话说,我想获得所有连续的 div.row

这是我正在使用的代码

foreach (pq('h3:contains("Specifications")', $profile_page)->nextAll('div.row') as $div) {

}

但它的作用是,它也会刮掉some text 4 div。

我也尝试过nextAll('div.row'),但结果相同。

所以我的问题是,我如何在&lt;h3&gt;Specifications&lt;/h3&gt; 之后获得所有连续的div.row,如果中间有任何其他标签,那么就停止。

PS:

纯 jQuery 的答案也将被接受,因为 phpQuery 库使用与 jQuery 相同的功能。

【问题讨论】:

    标签: php jquery html phpquery


    【解决方案1】:

    您可以使用:first 选择器获取第一个.row 元素,然后使用nextUntil() 捕获其余元素。试试这个:

    var $rows = $('.row:first').nextUntil(':not(.row)');
    

    如果您还想在匹配集中包含第一行,您可以使用addBack(),如下所示:

    var $rows = $('.row:first').nextUntil(':not(.row)').addBack();
    

    Working example

    【讨论】:

    • 遗憾的是,phpQuery 库中没有函数nextUntil ... :( 还有什么我可以做的吗???也许是 REGEX 解决方案?
    • 实际上我正在做网页报废,这个脚本将作为一个 cronjob 运行......所以我不能使用 jquery
    【解决方案2】:

    jQuery:

    $("h3").nextUntil("#pricing");
    

    捕获h3之后的所有元素,直到到达id为pricing的元素

    【讨论】:

    • 这不确定是否会有带有 ID 定价的 DIV ...如果中间有任何其他标签,我想停止获取下一个 div
    【解决方案3】:

    连续的 div,嗯?听起来你想要这样的东西:

    div.row:has(+ div.row),div.row + div.row
    

    我不知道PHPQuery是否支持,如果不支持你应该考虑切换。

    另一个想法是做h3 + .row,然后继续迭代@​​987654323@

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-26
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多