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

Beautiful Soup无法获取Trendyol商品页全部高清图片问题求助

问题原因
  • 代码缩进错误:__init__、saveImages方法未缩进在GetProductInfo类作用域内,类初始化时未执行页面渲染逻辑,解析的是未加载动态内容的原始静态页,因此无法识别动态生成的gallery-container节点
  • 平台懒加载策略:Trendyol默认仅将低分辨率占位图放在img标签的src属性,高清原图地址存储在data-src自定义属性中
  • CDN图片压缩规则:Trendyol的CDN图片URL带有尺寸标识(如/mn/、/sm/代表不同压缩尺寸),替换为原图标识/orj/即可获取无压缩原图
修复后代码

GetProductInfo.py

from bs4 import BeautifulSoup
from requests_html import HTMLSession
from os.path import basename
import requests
import os

class GetProductInfo:
    def __init__(self, link):
        session = HTMLSession()
        html_text = session.get(link)
        # 增加等待时长确保动态内容完全加载
        html_text.html.render(sleep=2)
        self.soup = BeautifulSoup(html_text.html.html, 'lxml')
        # 自动创建图片存储目录,避免目录不存在报错
        os.makedirs('images', exist_ok=True)

    def saveImages(self):
        # 定位商品画廊容器
        gallery = self.soup.find('div', class_='gallery-container')
        if not gallery:
            print("未找到商品画廊容器")
            return
        # 提取画廊内所有图片节点
        for img in gallery.find_all('img'):
            # 读取存储高清地址的data-src属性
            raw_img_url = img.get('data-src')
            if not raw_img_url or 'http' not in raw_img_url:
                continue
            # 替换URL中的压缩尺寸标识为原图标识
            hd_img_url = raw_img_url.replace('/mn/', '/orj/').replace('/sm/', '/orj/')
            with open(f"images/{basename(hd_img_url)}", "wb") as f:
                f.write(requests.get(hd_img_url).content)

test.py

from GetProductInfo import *
product = GetProductInfo("https://www.trendyol.com/aqua-di-polo-1987/unisex-kol-saati-apl12c195h02-p-3929108")
product.saveImages()
注意事项

首次运行requests-html的render方法会自动下载对应的Chromium内核,等待下载完成即可正常执行。如果遇到部分图片地址规则不同,可对比开发者工具中高清图的URL结构,调整对应的替换规则即可。

内容的提问来源于stack exchange,提问作者HASAN HÜSEYİN YÜCEL

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 14:33:00