请求协助:PHP抓取指定URL广告内容并在自有站点定制展示(含分页)
问题分析与解决方案
原代码失败的核心原因
- DOMNodeList无法直接输出:
getElementsByClassName()返回的是DOMNodeList对象,直接echo只会输出对象标识,不是HTML内容。 - 动态内容抓取失效:目标站点的广告列表大概率是JavaScript动态渲染的,
file_get_contents()只能获取初始静态HTML,拿不到JS加载后的广告数据。 - 反爬/跨域限制:直接用PHP请求第三方站点可能被反爬机制拦截,返回空内容或错误页面。
解决方案步骤
1. 正确抓取广告内容
情况1:页面为静态渲染(广告在初始HTML中)
修正PHP代码,遍历DOMNodeList并输出每个节点的HTML:
<?php $url = "https://www.finn.no/car/used/search.html?orgId=3553552&sort=PUBLISHED_DESC"; // 解决编码问题,避免乱码 $context = stream_context_create([ 'http' => [ 'header' => 'Accept-Charset: UTF-8' ] ]); $html = file_get_contents($url, false, $context); libxml_use_internal_errors(true); // 忽略HTML解析警告 $doc = new DOMDocument(); $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); libxml_clear_errors(); $ads = $doc->getElementsByClassName("ads__unit"); $output = ''; // 遍历节点,拼接HTML foreach ($ads as $ad) { $output .= $doc->saveHTML($ad); } ?> <!-- 自定义容器,用于添加样式 --> <div class="custom-ad-container"> <?php echo $output; ?> </div>
情况2:页面为动态渲染(广告由JS加载)
使用无头浏览器工具抓取动态内容,推荐用PHP的spatie/browsershot包(依赖Puppeteer):
# 先安装依赖 composer require spatie/browsershot npm install puppeteer
PHP代码示例:
<?php use Spatie\Browsershot\Browsershot; $url = "https://www.finn.no/car/used/search.html?orgId=3553552&sort=PUBLISHED_DESC"; $html = Browsershot::url($url) ->waitForSelector('.ads__unit') // 等待广告节点加载完成 ->bodyHtml(); // 只获取页面body内容 libxml_use_internal_errors(true); $doc = new DOMDocument(); $doc->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); libxml_clear_errors(); $ads = $doc->getElementsByClassName("ads__unit"); $output = ''; foreach ($ads as $ad) { $output .= $doc->saveHTML($ad); } ?> <div class="custom-ad-container"> <?php echo $output; ?> </div>
2. 自定义样式
在站点CSS中添加自定义样式,覆盖广告默认样式:
.custom-ad-container { background-color: #f5f5f5; /* 自定义背景 */ padding: 20px; border-radius: 8px; } .custom-ad-container .ads__unit { background: white; margin-bottom: 15px; border: 1px solid #eee; border-radius: 4px; padding: 10px; /* 其他自定义样式 */ }
3. 迁移分页功能
- 分析目标站点的分页URL结构:观察原站点分页按钮,URL通常带有
page参数(例如&page=2) - 在自有站点添加分页导航,传递
page参数到PHP脚本:
<div class="pagination"> <?php $currentPage = $_GET['page'] ?? 1; $prevPage = max(1, $currentPage - 1); $nextPage = $currentPage + 1; ?> <a href="?page=<?php echo $prevPage; ?>">上一页</a> <span>第 <?php echo $currentPage; ?> 页</span> <a href="?page=<?php echo $nextPage; ?>">下一页</a> </div>
- 修改PHP抓取URL,拼接
page参数:
$currentPage = $_GET['page'] ?? 1; $url = "https://www.finn.no/car/used/search.html?orgId=3553552&sort=PUBLISHED_DESC&page=" . $currentPage;
注意事项
- 确保遵守目标站点的服务条款,未经授权抓取内容可能违反规定
- 加入缓存机制,避免频繁请求第三方站点(例如用Redis或文件缓存抓取结果)
- 处理反爬限制:可以添加请求头模拟浏览器,设置合理的请求间隔
内容的提问来源于stack exchange,提问作者SigiNO
相关产品推荐
相关产品推荐

