首页 > 解决方案 > 在 PHP 中使用简单的 html dom 抓取数据奇数属性

问题描述

早上好,我需要从网站获取一些数据,我正在尝试一些解决方案,但目前我没有找到合适的解决方案。这是代码:

    <tr><td class="h-text-left"><a href="/soccer/peru/liga-1/binacional-llacuabamba/YasJ57j7/" class="in-match"><span><strong>Binacional</strong></span> - <span>Llacuabamba</span></a></td><td class="h-text-center"><a href="/soccer/peru/liga-1/binacional-llacuabamba/YasJ57j7/">2:1</a></td><td class="table-main__odds colored" data-oid="3o4fmxv464x0x9r5fh"><span><span><span data-odd="2.16"></span></span></span></td><td class="table-main__odds" data-oid="3o4fmxv498x0x0" data-odd="3.31"></td><td class="table-main__odds" data-oid="3o4fmxv464x0x9r5fi" data-odd="3.13"></td><td class="h-text-right h-text-no-wrap">Yesterday</td></tr>
<tr><td class="h-text-left"><a href="/soccer/peru/liga-1/carlos-stein-atletico-grau/EwcmMDIc/" class="in-match"><span>Carlos Stein</span> - <span>Grau</span></a></td><td class="h-text-center"><a href="/soccer/peru/liga-1/carlos-stein-atletico-grau/EwcmMDIc/">1:1</a></td><td class="table-main__odds" data-oid="3o4cvxv464x0x9r5a3" data-odd="2.32"></td><td class="table-main__odds colored" data-oid="3o4cvxv498x0x0"><span><span><span data-odd="2.99"></span></span></span></td><td class="table-main__odds" data-oid="3o4cvxv464x0x9r5a4" data-odd="3.10"></td><td class="h-text-right h-text-no-wrap">Yesterday</td></tr>

你可以看到 td class table-main__odds coloured 和 td class table-main__odds; 他们并不总是处于相同的位置。我尝试了这种方法:

...
    function print_odd($odd) {
    if (array_key_exists('data-odd', $odd->attr)) {
        return $odd->attr['data-odd'];
    }

    return $odd->children(0)->children(0)->children(0)->children(0)->attr['data-odd'];
}
...
        $odd1 = print_odd($odds[$b++]);
        $odd2 = print_odd($odds[$b++]);
        $odd3 = print_odd($odds[$b++]);
...

这段代码工作了几年,但我认为代码发生了一些变化有什么建议吗?

谢谢

编辑:这是页面地址:链接网站

标签: phphtmlsimple-html-dom

解决方案


我认为问题在于sinner HTML<td>s 在元素之间发生了变化或变化。所以有时你有 a<td data-odd="...和其他时候你有<td><span...<span data-odd="...。在这种情况下,也许您可​​以使用 some 更新您的函数,regex并从内部 HTMLpreg_match捕获部分。data-odd="..."例如:

/* 
 I assume $odd parameter is a <td> DOMElement
 let's say $odd is a <td> with this structure:
<td class="table-main__odds colored" data-oid="3o4cvxv498x0x0">
  <span><span><span data-odd="2.99"></span></span></span>
</td>
*/

function print_odd($odd) {
    // if <td> has data-odd attribute -> this will do
    if (array_key_exists('data-odd', $odd->attr)) {
        return $odd->attr['data-odd'];
    }

    // else, grab inner HTML of td
    // see https://stackoverflow.com/questions/2087103/how-to-get-innerhtml-of-domnode/39193507
    // maybe like this
    $td_html = $odd->C14N();
    $regex = '/data-odd=\"([0-9.]+)\"+?/';

    preg_match($regex, $td_html, $matches);

    if ($matches) {
        return $matches[1]; // "2.99" (string)
    }

    // if nothing is found
    return false;

}

推荐阅读