【问题标题】:Web scraping with PHP and HTML DOM Parser使用 PHP 和 HTML DOM Parser 进行 Web 抓取
【发布时间】:2020-01-31 19:27:30
【问题描述】:

我正在尝试在代码中抓取网站,但我会以表格格式。

$url='http://www.arbworld.net/en/moneyway';
    libxml_use_internal_errors( true );
    $dom=new DOMDocument;
    $dom->validateOnParse=false;
    $dom->recover=true;
    $dom->strictErrorChecking=false;
    $dom->loadHTMLFile( $url );
    libxml_clear_errors();


    $xp=new DOMXPath( $dom );
    $col=$xp->query('//table[@class="grid"]/tr[@class="belowHeader"]/td');

    if( $col->length > 0 ){
        foreach( $col as $node )echo $node->textContent;
    }

现在输出是这样的:

罗马尼亚联赛 I22.Dec 18:00:00 FCSBUniversitat2.063.33.999.9 %€ 2070.1 %€ 00 %€ 0€ 207 22.Dec 18:00:00 意大利甲级联赛 A22.Dec 11:30:00 亚特兰大AC米兰1.8844.499.7 %€ 21 5580.1 %€ 170.2 %€ 46€ 21 622 22.Dec 11:30:00 英格兰联赛 221.Dec 15:0 0:00

【问题讨论】:

    标签: php html parsing web-scraping


    【解决方案1】:

    您应该检索行而不是列(末尾没有 /td),然后简单地将所有内容放入 HTML 表中,每行一个 <tr>

    <?php
    // your current code
    
    $xp = new DOMXPath($dom);
    $rows = $xp->query('//table[@class="grid"]/tr[@class="belowHeader"]');
    ?>
    
    <table>
      <tbody>
      <?php foreach ($rows as $row): ?>
        <tr>
        <?php foreach ($row->childNodes as $col): ?>
          <?php if ($col->getAttribute('style') !== 'display:none'): ?>
            <?php foreach ($col->childNodes as $colPart): ?>
              <?php if ($colText = trim($colPart->textContent)): ?>
              <td><?= $colText ?></td>
              <?php elseif ($colPart instanceof DOMElement && $colPart->tagName === 'a'): ?>
                <?php
                $href = $colPart->getAttribute('href');
                if (strpos($href, 'javascript') !== 0):
                ?>
                <td><?= $colPart->getAttribute('href') ?></td>
                <?php endif ?>
              <?php endif ?>
            <?php endforeach ?>
          <?php endif ?>
        <?php endforeach ?>
        </tr>
      <?php endforeach ?>
      </tbody>
    </table>
    

    【讨论】:

    • 太棒了!最后一件事。如何将其分开:“80.9 %€ 245 063”并插入两个不同的列?
    • @FilippoSchiera 检查我上次的编辑。将原始列拆分为其子节点应该可以解决问题。
    • 第二次很棒。最后最后最后一件事。在网站的最后一个表中,有一列在 href --> ads.betfair.com/…" rel="nofollow" target="_blank">arbworld.net/flags/chart.png " alt="赔率统计">
    • 我会刮掉redirecturl=***betfair.com/exchange/football/…*** 之后我们也可以结束讨论了。非常非常感谢:)
    • @FilippoSchiera 我做了另一个编辑。不过,现在这有点太具体了。剩下的交给你。
    猜你喜欢
    • 2017-06-08
    • 2011-06-09
    • 1970-01-01
    • 2019-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 2012-08-12
    相关资源
    最近更新 更多