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

如何为Scrapy爬虫的回调函数添加关键字参数?

解决Crochet中Deferred.addCallback传递关键字参数的问题

你遇到的问题是因为Twisted的Deferred.addCallback并不支持callbackKeywords或cb_kwargs这类参数,这两个参数并非Twisted Deferred的标准用法。要给回调函数传递关键字参数,有两种可靠的实现方式:

方法1:直接在addCallback中传递关键字参数

Twisted的addCallback允许直接在回调函数后追加关键字参数,这些参数会和Deferred的执行结果一起传递给回调函数。示例代码:

@crochet.run_in_reactor
def scrape_with_crochet(req):
    eventual = crawl_runner.crawl(Spider, output_data = output_data,**req)
    # 直接传递关键字参数stash=5
    eventual.addCallback(finished_scrape, stash=5)

对应的finished_scrape函数需要定义接收该关键字参数:

def finished_scrape(result, stash=None):
    # 处理逻辑
    print(stash)  # 输出5

方法2:使用functools.partial包装回调函数

如果需要更灵活的参数绑定(比如提前绑定多个参数),可以用functools.partial把关键字参数预先绑定到回调函数上:

from functools import partial

@crochet.run_in_reactor
def scrape_with_crochet(req):
    eventual = crawl_runner.crawl(Spider, output_data = output_data,**req)
    # 用partial包装回调,绑定stash=5
    wrapped_callback = partial(finished_scrape, stash=5)
    eventual.addCallback(wrapped_callback)

这种方式下,finished_scrape的参数定义和方法1一致即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:02:10