from scrapy import log
from scrapy.http import request
from scrapy.item import baseitem
from scrapy.utils.request import request_fingerprint
from myproject.items import myitem
class ignorevisiteditems(object):
“””middleware to ignore re-visiting item pages if they
were already visited before.
the requests to be filtered by have a meta[‘filter_visited’]
flag enabled and optionally define an id to use
for identifying them, which defaults the request fingerprint,
although you’d want to use the item id,
if you already have it beforehand to make it more robust.
filter_visited = ‘filter_visited’
visited_id = ‘visited_id’
context_key = ‘visited_ids’
def process_spider_output(self, response, result, spider):
context = getattr(spider, ‘context’, {})
visited_ids = context.setdefault(self.context_key, {})
ret = []
for x in result:
visited = false
if isinstance(x, request):
if self.filter_visited in x.meta:
visit_id = self._visited_id(x)
if visit_id in visited_ids:
log.msg(“ignoring already visited: %s” % x.url,, spider=spider)
visited = true
elif isinstance(x, baseitem):
visit_id = self._visited_id(response.request)
if visit_id:
visited_ids[visit_id] = true
x[‘visit_id’] = visit_id
x[‘visit_status’] = ‘new’
if visited:
return ret
def _visited_id(self, request):
return request.meta.get(self.visited_id) or request_fingerprint(request)


Posted in 未分类