【问题标题】:DOMXPath Return ZeroDOMXPath 返回零
【发布时间】:2014-07-03 22:35:54
【问题描述】:

我正在尝试从网站中提取一些信息。我需要的信息包含在一个表中,我已经创建了一个查询来查找它。从 Chrome 使用控制台时,我可以看到表达式返回了我需要的表。但是当我设置 PHP 代码时,查询返回零。

这是来自 Chrome 控制台

这是我的 PHP 代码

$ch = curl_init($domain);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$cl = curl_exec($ch);
$dom = new DOMDocument();
@$dom->loadHTML($cl);
$xpath = new DOMXPath($dom);

$table = $xpath->query("//div[@id='content_fmainplace']//form/table/tbody/tr[15]//table");
echo $table->length;

有什么想法吗?我在这里错过了什么?

【问题讨论】:

  • 您是否尝试过不隐藏错误消息?
  • 真的很难从这里猜到,愿意分享网站链接吗?
  • @kevinabelita 这是链接,我需要的资料在2.1节下app.cfe.gob.mx/Aplicaciones/CCFE/Tarifas/Tarifas/…
  • @elgranchuy 网站的 html 结构多么令人痛苦! 2.1节的哪一部分?标题及其内容?
  • @kevinabelita 我知道,这是我每天都必须处理的事情 :(。无论如何...我想我发现了“错误”。似乎 tbody 无法正常工作或未被检测到不知何故。我不知道 Chrome/Firefox 是否将 tbody 标记添加到每个表或 DOMXPath 没有检测到它。我将查询更改为 //div[@id='content_fmainplace']//form/table//tr[15]//table 并且它现在可以工作了。

标签: php dom xpath domxpath


【解决方案1】:

你真的不需要定位 div。只需定位表的id。考虑这个例子:Sample Output

$domain = 'http://app.cfe.gob.mx/Aplicaciones/CCFE/Tarifas/Tarifas/tarifas_casa.asp?Tarifa=DACTAR1E&Temporada4=Verano&Anio=2014&imprime=&Periodo=4&mes2=a+septiembre.&mes=1';
$ch = curl_init($domain);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$cl = curl_exec($ch);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($cl);
libxml_clear_errors();
$xpath = new DOMXPath($dom);

// target the title
$title = $values = $xpath->query('//table[@id="Table1"]/tr[1]/td[1]/form/table/tr[14]')->item(0)->nodeValue; // title rows
$rows = $xpath->query('//table[@id="Table1"]/tr[1]/td[1]/form/table/tr[15]/td/table/tr');
$row_values = array();

// process td elements
foreach($rows as $index => $row) {
    foreach($row->childNodes as $td) {
        // clean up
        $row_values[$index][] = preg_replace( '/\s+/', '', trim($td->nodeValue));
    }
    // clean up again
    $row_values[$index] = array_filter($row_values[$index]);
}    

?>

<!-- print them -->
<h1><?php echo $title; ?></h1>
<table cellpadding="10">
<?php foreach($row_values as $values): ?>
    <tr><?php foreach($values as $value): ?>
        <td><?php echo $value; ?></td>
    <?php endforeach; ?></tr>
<?php endforeach; ?>
</table>

【讨论】:

  • 是的,我确实看到了表格 ID,但问题是此链接适用于 1E 部分的 1 月份费率,如果您将部分更改为不同的 1A、1B、1C 或 1D,代码将更改为一点点,其中一些表ID丢失了。我注意到我使用的查询适用于所有这些。
猜你喜欢
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 2021-09-23
  • 2016-11-24
  • 2021-10-24
  • 2017-11-19
  • 2015-01-23
  • 2016-11-24
相关资源
最近更新 更多