You need to enable JavaScript to run this app. Python Scrapy 如何提取页面中的指定单张图片?
优惠活动
大模型
产品
解决方案
定价
更多

Python Scrapy 如何提取页面中的指定单张图片?

代码修改实现单张指定图提取

问题原因

原代码response.xpath('//img/@src').getall()会抓取页面上所有img元素的src属性,包含站点logo、功能图标、装饰素材等无关图片,没有针对目标产品主图做精准匹配,因此无法满足仅提取指定单张图的需求。

核心调整思路

根据你给出的目标图片URL特征做精准筛选:你需要提取的图统一为站点/photo/路径下、文件名带foto_w720_前缀的产品主图,因此不需要抓取全量图片,只需匹配符合该特征的单个图片地址,再自动拼接为绝对URL即可。

具体修改步骤

  1. 补全缺失的基础导入:原代码直接使用Spider类但未引入对应依赖,会直接报运行错误
  2. 替换parse_book方法内的图片提取逻辑,把原来的全量抓取改成特征匹配的单值提取,同时对匹配到的路径做绝对URL拼接,和实际站点的完整图片地址格式对齐
  3. 兼容电商站常见的图片懒加载场景:部分站点主图不会直接写在src属性里,而是存在data-src等自定义属性中,选择器可做兼容适配

修改后的完整代码

from scrapy.http import Request
from scrapy.spiders import Spider  # 补全缺失的Spider基类导入


class BooksSpider(Spider):
    name = 'books'
    allowed_domains = ['eshop.erhanteknik.com.tr']
    start_urls = ['http://eshop.erhanteknik.com.tr/urunlerimiz?categoryId=1']

    def parse(self, response):
        books = response.xpath('//h3/a/@href').getall()
        for book in books:
            absolute_url = response.urljoin(book)
            yield Request(absolute_url, callback=self.parse_book)

        # 处理下一页
        next_page_url = response.xpath('//a[@rel="next"]/@href').extract_first()
        absolute_next_page_url = response.urljoin(next_page_url)
        yield Request(absolute_next_page_url)
        
    def parse_book(self, response):
        title = response.css('h1::text').extract_first()
        # 精准匹配带/photo/路径、foto_w720_前缀的目标主图,兼容懒加载场景
        raw_img_url = response.xpath(
            '''//img[
                (contains(@src, '/photo/') and contains(@src, 'foto_w720_')) 
                or 
                (contains(@data-src, '/photo/') and contains(@data-src, 'foto_w720_'))
            ]/@src | 
            //img[
                (contains(@src, '/photo/') and contains(@src, 'foto_w720_')) 
                or 
                (contains(@data-src, '/photo/') and contains(@data-src, 'foto_w720_'))
            ]/@data-src'''
        ).get()
        # 拼接为绝对URL,匹配目标完整图片地址格式
        image_url = response.urljoin(raw_img_url) if raw_img_url else None
        
        yield {
            'title': title,
            'image_url': image_url,
        }
  • 简化适配无懒加载的场景:如果确认站点主图直接写在src属性上,可把图片匹配选择器简化为response.xpath('//img[contains(@src, "foto_w720_")]/@src').get(),减少代码冗余。

效果说明

  • 提取到的图片地址会和你举的示例地址格式完全一致:http://eshop.erhanteknik.com.tr/photo/foto_w720_604e44853371a920a52b0a31a3548b8b.jpg
  • 不会抓取页面上的logo、功能按钮图标、其他规格小图等无关资源
  • 自动适配相对路径/绝对路径、普通加载/懒加载的不同场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.30 17:15:01