刮HTML和&使用简单HTML DOM计算孩子

时间:2014-01-31 18:32:47

标签: php dom web-scraping simple-html-dom scrape

我正在尝试从网站收集数据,并想要计算另一个元素中的元素数量。定位不同的DOM元素工作正常,但由于某种原因,下面示例中的$ count变量保持为“0”。我可能错过了一些非常愚蠢的东西,但我似乎无法找到它。

网站上的HTML如下:

<div id="list_options">
    <div class="list_mtgdef_option pointer">
        <div class="list_mtgdef_foildesc shadow">
        </div>
        <div class="list_mtgdef_stock tooltip">
            <div class="list_mtgdef_stock_left">
                <span class="foil008469_1 block  "></span>
                <span class="foil008469_2 block  transparency_25"></span>
            </div>
            <div class="list_mtgdef_stock_right">
                <span class="008469_8 block  "></span>
                <span class="008469_7 block  "></span>
                <span class="008469_6 block  "></span>
                <span class="008469_5 block  "></span>
                <span class="008469_4 block  "></span>
                <span class="008469_3 block  "></span>
                <span class="008469_2 block  "></span>
                <span class="008469_1 block  "></span>
            </div>
        </div>
    </div>
</div>

这是我正在使用的php:

$array = array();

foreach($html->find('#list_options .list_mtgdef_option') as $element) {
    $count = 0;

    foreach($element->find('.list_mtgdef_stock', 0)->childNodes(1)->childNodes as $node) {
        if(!($node instanceof \DomText))
            $count++;
    }

    $row = array(
        'stock' => strval($count)
    );

    array_push($array, $row);

}
echo json_encode($array);

3 个答案:

答案 0 :(得分:2)

确实很傻:()

$element->find('.list_mtgdef_stock', 0)->childNodes(1)->childNodes()

答案 1 :(得分:2)

你可以这样做:

count($element->find('.list_mtgdef_stock > *[2] > *'))
//=>8

答案 2 :(得分:1)

我用来自孩子的count元素解决了:

$element= $element->find('.list_mtgdef_stock', 0);
count($element->children())