我做了一只蜘蛛,它可以在cdiscount网站上收集数据。然而,每次我刮超过320页的一个类别,我有503错误和蜘蛛关闭。
如何处理这个问题?我尝试过更改用户代理并使用这样的代理池:
def __init__(self, *args, **kwargs):
super(CdiscountSpider, self).__init__(*args, **kwargs)
self.proxy_pool = ['49.236.220.238:52840', '181.112.41.50:33381', '50.235.111.161:45126']
(...)
request = scrapy.Request(url, callback=self.parse_dir_contents) #on accède au contenu des catégories
request.meta["proxy"] = random.choice(self.proxy_pool)
yield request但没起作用。请注意,任何帮助都非常感谢:)
发布于 2018-10-19 12:56:30
您可以拥有一个下载中间件,它不断地使用新的代理重新尝试具有503响应的URL,直到它们被成功地刮掉。
创建一个名为custom_middleware.py的文件
import random
import logging
class CustomMiddleware(object):
proxy_pool = ['49.236.220.238:52840', '181.112.41.50:33381', '50.235.111.161:45126']
def process_request(self, request, spider):
request.meta['proxy'] = “http://“ + random.choice(self.proxy_pool)
def process_response(self, request, response, spider):
if response.status in [503]:
logging.error("%s found for %s so retrying"%(response.status, response.url))
req = request.copy()
req.dont_filter = True
req.meta['proxy'] = “http://“ + random.choice(self.proxy_pool)
return req
else:
return response在您的settings.py中,只需启用该中间件
DOWNLOADER_MIDDLEWARES = {
'scrapy.contrib.downloadermiddleware.httpproxy.HttpProxyMiddleware': 1,
'YOUR_PROJECT_PATH.custom_middleware.CustomMiddleware': 200,
}https://stackoverflow.com/questions/52892533
复制相似问题