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

PHP DOMCrawler抓取OG标签商品图异常问题求助

DOMCrawler爬取商品主图返回logo修复方案

问题原因

该品牌网站近期调整了页面meta标签排列规则,og:image 标签的首个节点固定配置为品牌logo,商品对应的主图og:image标签排列在后续节点;同时针对未携带标准浏览器请求头的爬虫请求,网站会返回简化版页面,仅保留全局logo的og:image节点。

修复步骤

1. 调整请求配置,避免触发反爬简化策略

发起爬取请求时需携带标准浏览器头,示例Guzzle配置如下:

$client = new \GuzzleHttp\Client([
    'headers' => [
        'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        'Referer' => 'https://www.toryburch.com/',
        'Accept-Language' => 'en-US,en;q=0.9'
    ]
]);

2. 优化页面元素筛选逻辑

提供两种稳定性较高的实现方案:

方案A:调整og:image筛选偏移+页面节点兜底

protected function getImage(Crawler $crawler)
{
    $image = null;
    $ogImageNodes = $crawler->filter('meta[property="og:image"]');
    // 跳过首个logo节点,取后续商品图节点
    if ($ogImageNodes->count() > 1) {
        $image = $ogImageNodes->eq(1)->attr('content');
        // 校验是否仍为logo,继续向后偏移
        if (str_contains($image, 'medallion-navy')) {
            $image = $ogImageNodes->count() > 2 ? $ogImageNodes->eq(2)->attr('content') : $image;
        }
    }
    // 兜底逻辑:直接取商品展示区块的图片属性
    if (empty($image) || str_contains($image, 'medallion-navy')) {
        $productImgNodes = $crawler->filter('.product-image-container img');
        if ($productImgNodes->count() > 0) {
            $image = $productImgNodes->first()->attr('src') ?: $productImgNodes->first()->attr('data-src');
        }
    }
    return $image;
}

方案B:读取结构化JSON-LD数据(更稳定)

该方案直接读取页面内置的商品结构化数据,不受前端布局调整影响,准确率更高:

protected function getImage(Crawler $crawler)
{
    $image = null;
    $jsonLdNodes = $crawler->filter('script[type="application/ld+json"]');
    if ($jsonLdNodes->count() > 0) {
        $productData = json_decode($jsonLdNodes->first()->text(), true);
        if (isset($productData['image']) && is_array($productData['image'])) {
            $image = reset($productData['image']);
        }
    }
    return $image;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 19:06:05