代理队列结束时停止抓取



我有一个代理中间件,它返回代理不超过 3 次,之后代理不能再使用。

假设我有 3 个代理,每个代理使用 3 次。我可以解析 9 个项目

而且有25个项目在刮擦的队列中。当我用完代理时,如何清理队列?还是强行阻止一个乞丐?

class CityPolygonsSpider(scrapy.Spider):
name = 'city_polygons'
cities_url = 'http://127.0.0.1:8001/privat-api/cities/?country_code__in=ru,ua,kz,by'
custom_settings = {
    'ITEM_PIPELINES': {
        'geonames.pipelines.CityPolygonPipeline': 300
    },
    'DOWNLOADER_MIDDLEWARES': {
        'geonames.middlewares.ProxyMiddleware': 100,
    },
}
def start_requests(self):
    yield Request(url=self.cities_url, callback=self.parse_next, dont_filter=True)
def parse_next(self, response):
    raw = json.loads(response.body_as_unicode())
    if raw['next']:
        yield Request(url=raw['next'], callback=self.parse_next, dont_filter=True)
    for city in raw['results']:
        city_href = self.search_url + '?' + city['name']
        request = Request(
            url=city_href, callback=self.parse_cities, dont_filter=True)
        request.meta['city_id'] = city['id']
        yield request
def parse_cities(self, response):
    result = json.loads(response.body_as_unicode())['data']
    if result.get('exactResult'):
            yield CityPolygonItem(** result.get('exactResult'))

您可以在代理中间件中跟踪代理使用情况的计数。我会使用一个以代理主机:端口组合为键的字典,并点击计数作为值。在每个代理分配中检查字典中的每个条目。如果没有命中计数小于 3 的代理,请引发 CloseSpider 异常。

以下是文档的相关部分:

https://doc.scrapy.org/en/latest/topics/exceptions.html?highlight=CloseSpider

最新更新