Laravel中使用friendofphp/goutte爬取表格时格式及链接还原问题
解决Laravel中Goutte爬取Google Scholar表格数据的问题
问题分析
你的原代码存在几个核心问题:
- 仅针对表头容器
#gsc_a_t遍历,未处理表格主体的行数据 - 只提取了第一个表头单元格和第一个数据单元格,未遍历所有单元格
dd()直接终止循环,无法获取完整数据
修正后的爬取代码(控制器中)
use Goutte\Client; $client = new Client(); $crawler = $client->request('GET', 'https://scholar.google.com/citations?user=EnegzCwAAAAJ&hl=en&oi=ao'); // 初始化存储表格数据的数组 $tableData = [ 'headers' => [], // 表头数组 'rows' => [] // 行数据,每行包含td文本和链接 ]; // 提取表头 $crawler->filter('#gsc_a_t th')->each(function ($th) use (&$tableData) { $tableData['headers'][] = trim($th->text()); }); // 提取表格主体的每一行 $crawler->filter('#gsc_a_b .gsc_a_tr')->each(function ($tr) use (&$tableData) { $rowTds = []; $rowTdLinks = []; // 遍历当前行的所有td单元格 $tr->filter('td')->each(function ($td) use (&$rowTds, &$rowTdLinks) { $rowTds[] = trim($td->text()); // 提取td内的链接(如果存在) $linkNode = $td->filter('a')->first(); $rowTdLinks[] = $linkNode->count() ? $linkNode->attr('href') : null; }); $tableData['rows'][] = [ 'tds' => $rowTds, 'tdLinks' => $rowTdLinks, ]; }); // 将数据传递到视图 return view('scholar-table', compact('tableData'));
视图渲染代码(scholar-table.blade.php)
通过循环数组还原原始表格格式及链接:
<table border="1" cellpadding="8" cellspacing="0" style="border-collapse: collapse;"> <thead> <tr> @foreach($tableData['headers'] as $header) <th>{{ $header }}</th> @endforeach </tr> </thead> <tbody> @foreach($tableData['rows'] as $row) <tr> @foreach($row['tds'] as $index => $tdContent) <td> @if($row['tdLinks'][$index]) <!-- 补全Google Scholar的域名,因为爬取的是相对链接 --> <a href="https://scholar.google.com{{ $row['tdLinks'][$index] }}" target="_blank"> {{ $tdContent }} </a> @else {{ $tdContent }} @endif </td> @endforeach </tr> @endforeach </tbody> </table>
关键说明
- Google Scholar的表格行使用
.gsc_a_tr类标识,需通过该选择器定位所有行 - 爬取的链接为相对路径,需补全
https://scholar.google.com域名才能正常访问 - 数组结构分层清晰,
headers存表头文本,rows数组中每个元素包含当前行的所有td文本和对应链接,方便视图循环渲染
内容的提问来源于stack exchange,提问作者Ana Fernandes
相关产品推荐
相关产品推荐

