【问题标题】:Scrape HTML table data and create XML or JSON doc抓取 HTML 表格数据并创建 XML 或 JSON 文档
【发布时间】:2012-06-05 15:41:41
【问题描述】:

我需要从网站上的表格中抓取一些网站数据,并创建一个将由应用程序使用的 XML 或 JSON 文档。我在获取以下数据时遇到了一些问题。

表格如下所示:

<table border="0" cellpadding="3" cellspacing="0" bgcolor="#DDEEFF" width="100%">
<tr>
<td width="20%" ><font face="Verdana, Arial" size="1">SRC</a></td></font>
    <td width="58%" ><font face="Verdana, Arial" size="1"><a href="http://example.com/this/news?id=1&by=today" onMouseOver="a('Open Bulletin');return true" onMouseOut="b()">Welcome</font></a></td>
<td width="17%" align="center"><font face="Verdana, Arial" size="1">Event</td></font>
    </tr>   

<tr>
<td width="20%" ><font face="Verdana, Arial" size="1">FMD</a></td></font>
    <td width="58%" ><font face="Verdana, Arial" size="1"><a href="http://example.com/this/news?id=2&by=today" onMouseOver="a('Open Bulletin');return true" onMouseOut="b()">Another News</font></a></td>
<td width="17%" align="center"><font face="Verdana, Arial" size="1">Updates</td></font>
    </tr>   
</td>

我想创建一个如下所示的 XML 提要或 JSON:

<bulletins>
    <title>Welcome</title>
    <id>1</id>
    <type>News</type>
</bulletins>

<bulletins>
    <title>Another News</title>
    <id>2</id>
    <type>Updates</type>
</bulletins>

这是我当前的代码:

<?php
$body = explode('<table border="0" cellpadding="3" cellspacing="0" bgcolor="#DDEEFF" width="100%">', $html);

$xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><xml />");

$rows = array();
foreach (array_slice(explode('<tr>', end($body)), 1) as $row)
{   
    preg_match('#<a.*?href="(.*?)".*?>(.*?)</a>#i', $row, $title);
    preg_match('/<a.*href="(.*)".*>(.*)<\/a>/iU', $row, $id);
   // preg_match('/type">([^<]+)<\/td>/', $row, $type); 

    $node = $xml->addChild('bulletins');

    $node->addChild('title', $title[1]);
    $node->addChild('id', $id[1]);
   // $node->addChild('type', $due[1]);
}

header('Content-Type: text/xml');
echo $xml->asXML();
?>

但我遇到了这个问题

<xml>
    <bulletins>
        <title>http://example.com/this/news?id=1</title>
        <id>http://example.com/this/news?id=1</id>
    </bulletins>
    <bulletins>
        <title>http://example.com/this/news?id=2</title>
        <id>http://example.com/this/news?id=2</id>
    </bulletins>
</xml>

【问题讨论】:

  • 那么,您遇到了什么问题? 它不起作用?是这样吗?
  • 感谢您的回复,问题已更新。
  • It's much easier to parse HTML with DOM ... 正则表达式在这件事上是浪费时间。
  • 但是使用 DOM 获取数据真的很难

标签: php xml xpath screen-scraping web-scraping


【解决方案1】:

这里有一个简单的例子让你开始只使用 dom 函数:

$dom = new DOMDocument();
@$dom->loadHTMLFile(url);
$xpath = new DOMXPath($dom);

$xml = new DOMDocument();
foreach($xpath->query('//table/tr') as $tr) {
  $bulletin = $xml->appendChild($xml->createElement("bulletin"));
  $title = $xpath->query('.//td[2]//a', $tr)->item(0)->nodeValue;
  $bulletin->appendChild($xml->createElement("title",$title));
  $type = $xpath->query('.//td[3]/font', $tr)->item(0)->nodeValue;
  $bulletin->appendChild($xml->createElement("type",$type));
}
echo $xml->saveXML();

【讨论】:

    【解决方案2】:

    主要问题是 HTML 一开始就无效,因此大多数 PHP XML/HTML 解析器在尝试解析这个特定的 HTML 表时会失败。我使用PHP Simple HTML DOM Parser 将您的表格转换为 JSON。此代码假定 table.html 仅包含您在上面指定的表。

    <?php
    include 'simplehtmldom/simple_html_dom.php';
    
    $html = file_get_html('table.html');
    
    $row_count = 0;
    
    foreach($html->find('tr') as $row) {
      $row_count++;
      foreach($html->find('td') as $cell) {
        $cell_text = $cell->plaintext;
        // There are no CSS classes or IDs to differentiate between columns in the
        // table, so we're using the width instead
        switch ($cell->attr['width']) {
          case '58%':
            $bulletins[$row_count]['title'] = $cell_text;
            break;
          case '17%':
            $bulletins[$row_count]['type'] = $cell_text;
            break;
        }
        $bulletins[$row_count]['id'] = $row_count;
      }
    }
    
    // Remove the invalid </a> tags from the cell text, and convert to JSON
    $json = str_replace('<\/a>', '', json_encode($bulletins));
    
    // Output:
    // {"1":{"id":1,"title":"Another News","type":"Updates"},"2":{"id":2,"title":"Another     News","type":"Updates"}}
    echo $json;
    
    ?>
    

    【讨论】:

    • 简单的 html dom 实际上比基于 libxml2 的库(例如 php 内置的库)更容易失败。
    【解决方案3】:

    假设您有一个有效的 HTML 表格,我已经为您编写了一个脚本: https://github.com/tremblay/HTML-Table-to-JSON

    使用这种格式的表格,您将运行 htmlToJSON('url.com', false, null, null, null, true);

    【讨论】:

      猜你喜欢
      • 2011-11-10
      • 2020-07-04
      • 2018-05-27
      • 1970-01-01
      • 2012-02-04
      • 2021-03-04
      • 1970-01-01
      • 2018-12-26
      • 2020-11-08
      相关资源
      最近更新 更多