Python中Scrapy的Request出错后,在errback函数里如何跳回正常流程?
Request 失败,程序跳转到 errback 的函数里之后还能重新跳回去继续执行程序吗?
我因为 IP 代理用不了 Request 没成功,在 error 里删除该 IP 代理后怎么继续 Request 之前没成功的 url 呢? 就有点像汇编里的跳转。
Python中Scrapy的Request出错后,在errback函数里如何跳回正常流程?
如果我有描述不清的话请看: https://stackoverflow.com/questions/48840526/using-scrapy-how-can-i-jump-back-to-the-point-where-requests-errback-function-w
在Scrapy里,如果Request在errback里处理完错误后想跳回正常流程,直接yield一个新的Request就行,带上原来的回调函数。
比如你抓一个页面,出错了,在errback里记录日志或者重试,然后重新发起同一个请求,让正常回调接着处理:
import scrapy
from scrapy.http import Request
class MySpider(scrapy.Spider):
name = 'example'
start_urls = ['http://example.com']
def parse(self, response):
# 正常解析逻辑
yield {'title': response.css('title::text').get()}
def parse_errback(self, failure):
# 错误处理,比如打印错误或重试
self.logger.error(f'Request failed: {failure.value}')
# 重新发起同一个请求,跳回正常流程
yield Request(
url=failure.request.url,
callback=self.parse, # 指定正常回调
errback=self.parse_errback, # 错误时还可以再走这里
dont_filter=True # 避免被去重
)
在启动Request时,同时指定callback和errback:
yield Request(
url='http://example.com',
callback=self.parse,
errback=self.parse_errback
)
这样,出错时会进入parse_errback,在里面再yield同一个Request并指定callback=self.parse,就回到正常流程了。
总结:在errback里重新yield带正常callback的Request。
回调的 failure 里有 request 对象
有是有,可是这达不到我的目的-。-
改写下载器中间件不就行啦
你应该是想重试吧,你可以参考一下 RetryMiddleware。写了一个类继承 RetryMiddleware,process_exception 里边做的重试。

