我有一个循环,如果后续yield请求的response.status为404,我会尝试中断该循环。我正在迭代页码,但不知道有多少页可用。最终,我将到达一个页面,该页面将是404,并且我希望它打破while循环。我已将其硬编码为40页,但超过40页
def parse(self, response):
cat = json.loads(response.body_as_unicode())
for c in cat:
while **RESPONSE.STATUS == 200**:
url = 'http://www.url.com/'+str(c)+'/'+str(page)+'.json'
page += 1
yield Request(url, callback=self.parse_cats)
def parse_cats(self, response):
if response.status == '404':
**BREAK ABOVE LOOP**
我看着Request(errback =),但是不确定这是否是正确的方法。
任何帮助将不胜感激!
由于Scrapy基于一个名为的异步网络库twisted
-该行为是非阻塞和异步的。您不能中断请求回调的循环。
但是,您可以具有某种seen_404
可以在Spider实例上使用的标志。一旦你看到404
的状态-一套它True
并打破循环的情况下,self.seen_404
是True
。这不是一个可靠的解决方案,因为这又是异步的-您将不知道在调用回调并将seen_404
其设置为时循环经过了多少次迭代True
。但是,例如,如果您知道在一个404
页面之后,所有接下来的页面也将具有404
状态-那么这可能没问题:
def parse(self, response):
cat = json.loads(response.body_as_unicode())
for c in cat:
if self.seen_404:
break
url = 'http://www.url.com/'+str(c)+'/'+str(page)+'.json'
page += 1
yield Request(url, callback=self.parse_cats)
def parse_cats(self, response):
if response.status == '404':
self.seen_404 = True
另一种选择是通过传递请求列表(队列)以使其在请求本身内部(内部)来使其同步meta
:
def parse(self, response):
cat = json.loads(response.body_as_unicode())
urls = ['http://www.url.com/%s/%s.json' % (c, page)
for page, c in enumerate(cat)] # if you want page to start with 1: enumerate(cat, start=1)
url = urls.pop(0)
yield Request(url, meta={'urls': urls}, callback=self.parse_cats)
def parse_cats(self, response):
if response.status == '404':
# stop crawling
raise CloseSpider('404 found at %s' % response.url)
urls = response.meta['urls']
try:
url = urls.pop(0)
except IndexError:
raise CloseSpider('No more urls to go')
yield Request(url, meta={'urls': urls}, callback=self.parse_cats)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句