【问题标题】:Screen scraping a two-column table with PHP使用 PHP 抓取一个两列表的屏幕
【发布时间】:2013-10-15 19:44:44
【问题描述】:

听起来很简单,但我对整个屏幕抓取的东西很陌生。我拥有的是一个远程站点http://www.remotesite.com(用于示例目的),它有一个具有如下结构的调度表:

<table>
  <tr>
    <td class="team">
      Team 1
    </td>
    <td class="team">
      Team 2
    </td>
  </tr>
</table>

根据当天进行的比赛数量,表格中填充了动态范围的条目,其中第 1 队对第 2 队等。

我已经构建了我的 scraper 来获取表格中列出的所有团队的列表,并且它可以成功运行。代码如下:

<?php
// Load Simple DOM
    include_once("simple_html_dom.php");
    
// Scrape the Schedule
    libxml_use_internal_errors(true);
    $dom = new DOMDocument();
    $html = file_get_html("http://www.remotesite.com/schedule.htm");
    
    // Load HTML
        $dom->loadHTML($html);
        $xpath = new DOMXPath($dom);

    // Get all the Teams
        $my_xpath_query = "//table//td[contains(@class, 'team')]";
        $result_rows = $xpath->query($my_xpath_query);

?>

为了回显我有这个代码:

<?php
    // Display the schedule
        foreach ($result_rows as $result_object){
            echo $result_object->nodeValue;
        }
?>

但是,这样做会像这样呼应团队:

Team1Team2Team3Team4Team5Team6 etc, etc.

它以正确的顺序让正在互相比赛的球队对,但我需要做的基本上是按照我获取表格的方式在表格中回显。

提前感谢您能给我的任何帮助!

【问题讨论】:

  • "what I need to do is基本上以与获取表格相同的方式回显表格"是什么意思?
  • 我想要完整地获取表格并将其从我的脚本中回显到屏幕上。
  • 那为什么要搜索//table//td...?为什么不只是对表本身进行 XPath 查询?
  • 我可以这样做,但如果他们添加任何其他列,那么我最终可能会得到我不想要或不需要的其他信息。
  • 那么你想要完整地获得表格,那么。

标签: php dom simple-html-dom screen-scraping


【解决方案1】:

根据您对我的问题的回答,我建议您这样做:

$rows = '';
$teams = array();

// Pull team names into array
foreach ($result_rows as $result_object){
   $teams[] = $result_object->nodeValue;
}

// Extract two teams per table row
while(count($teams)){
   $matchup = array_splice($teams, 0, 2);
   $rows .= '<tr><td>'.implode('</td><td>', $matchup).'</td></tr>';
}

// Write out the table
echo "<table>$rows</table>';

【讨论】:

  • 感谢您的回复和迄今为止的帮助,非常感谢。当我运行您的示例时,我得到“致命错误:超过 30 秒的最大执行时间”
  • 哎呀,错字了。尝试上述方法(具体而言,将 args 固定为 array_splice
猜你喜欢
  • 2012-04-14
  • 1970-01-01
  • 2011-06-03
  • 1970-01-01
  • 1970-01-01
  • 2011-06-09
  • 2010-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多