You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Laravel Goutte/DOMCrawler提取DOM元素报错:节点列表为空

解决Symfony DomCrawler解析表格时"The current node list is empty"错误

你遇到的问题是选择器写法错误导致的,先还原你的场景:

目标HTML结构

<div class="details">
  <table>
    <tr>
      <th class="field">Title</th>
      <td class="value">Laravel for Noobs</td>
    </tr>
    <tr>
      <th class="field">Type</th>
      <td class="value">PDF Book</td>
    </tr>
  </table>
</div>

需求

遍历每个<tr>,提取<th class="field">和<td class="value">的文本,生成如下数组:

$details = [
    ['field' => 'Title', 'value' => 'Laravel for Noobs'],
    ['field' => 'Type', 'value' => 'PDF Book']
];

错误原因分析

你写的选择器th .field和td .value是后代选择器,意思是找<th>内部class为field的子元素,但实际上<th>本身就带有field类,<td>本身带有value类,空格的存在让选择器找错了目标,导致节点列表为空。

修正后的代码

$details = [];
$crawler->filter('.details table tr')->each(function ($node) use(&$details) {
    // 修正选择器:去掉空格,直接用「标签+类」的绑定写法
    $field = $node->filter('th.field')->first()->text();
    $value = $node->filter('td.value')->first()->text();
    
    $details[] = [
        'field' => $field,
        'value' => $value
    ];
});

关于节点二次过滤的疑问

完全支持!DomCrawler的each()方法里的$node就是当前遍历到的<tr>节点,你可以在这个节点上继续调用filter()查找它的子元素,这正是你需要的用法,只是之前选择器写错才触发了错误。

内容的提问来源于stack exchange,提问作者Latheesan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:48:03