Python自定义scrapy中间模块避免重复采集的方法

yipeiwu_com5年前Python基础

本文实例讲述了Python自定义scrapy中间模块避免重复采集的方法。分享给大家供大家参考。具体如下:

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,
                level=log.INFO, 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:
        ret.append(MyItem(visit_id=visit_id, visit_status='old'))
      else:
        ret.append(x)
    return ret
  def _visited_id(self, request):
    return request.meta.get(self.VISITED_ID) or request_fingerprint(request)

希望本文所述对大家的Python程序设计有所帮助。

相关文章

python转换字符串为摩尔斯电码的方法

本文实例讲述了python转换字符串为摩尔斯电码的方法。分享给大家供大家参考。具体实现方法如下: chars = ",.0123456789?abcdefghijklmnop...

Python3获取拉勾网招聘信息的方法实例

Python3获取拉勾网招聘信息的方法实例

前言 为了了解跟python数据分析有关行业的信息,大概地了解一下对这个行业的要求以及薪资状况,我决定从网上获取信息并进行分析。既然想要分析就必须要有数据,于是我选择了拉勾,冒着危险深入...

python遍历 truple list dictionary的几种方法总结

实例如下: def TestDic1(): dict2 ={'aa':222,11:222} for val in dict2: print val def Tes...

Python sys.path详细介绍

如何将路径“永久"添加到sys.path? sys.path是python的搜索模块的路径集,是一个list 复制代码 代码如下:['', 'C:\\WINDOWS\\system32\...

在PYQT5中QscrollArea(滚动条)的使用方法

在PYQT5中QscrollArea(滚动条)的使用方法

如下所示: import sys from PyQt5.QtWidgets import * class MainWindow(QMainWindow): def __in...