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

如何根据分页条件发送Scrapy请求并返回对应响应

问题分析与修复方案

问题根源

当目标URL无分页时,process_link函数直接return response,但Scrapy的回调函数中仅return响应不会触发后续的get_content回调——只有通过yield请求或生成器输出,才能让响应进入下一个处理环节,这就是无分页URL无法进入get_content的原因。

修复代码

修改process_link的else分支,让无分页的URL也将响应传递给get_content处理:

def parse_item(self, response):
    yield scrapy.Request(
        url=response.url, 
        callback=self.process_link,  
        meta={
            'splash': {
                'args': {'wait': 0.5},
                'endpoint': 'render.html', 
            }       
        },
        dont_filter=True
    )    

def process_link(self, response):
    next_page = response.xpath("//*[@id='pagination']/a[last()-1]//@href").extract_first()
    
    if next_page is not None:
        print('Check if next page is paginated------------------------------------', response.url)
        yield scrapy.Request(
            url=response.url, 
            callback=self.get_content,
            meta={
                'splash': {
                    'args': {'wait': 5, 'lua_source': self.script},
                    'endpoint': 'execute', 
                } 
            },
            dont_filter=True
        )
    else:
        # 无分页时,同样将响应传给get_content处理
        yield scrapy.Request(
            url=response.url, 
            callback=self.get_content,
            meta={
                'splash': {
                    'args': {'wait': 5, 'lua_source': self.script},
                    'endpoint': 'execute', 
                } 
            },
            dont_filter=True
        )
        # 若不需要重新发起请求,可直接调用get_content并yield结果(适合无需二次渲染的场景):
        # for result in self.get_content(response):
        #     yield result

def get_content(self, response):
    print('000000000000000000000000000000', response.url)
    # 此处添加内容提取逻辑

说明

  • 无分页URL现在会和有分页URL走相同的处理流程,确保响应能进入get_content函数。
  • 如果不需要重新发起Splash请求,可选择直接调用get_content并yield其返回结果,减少重复请求开销。

内容的提问来源于stack exchange,提问作者benjamin olise

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 06:06:05