【问题标题】:scrapy with each item pipeline wrapped within spider file将每个项目管道包装在蜘蛛文件中的scrapy
【发布时间】:2015-06-12 16:56:59
【问题描述】:

我在一个项目中使用了scrapy,项目管道专为需要插入数据库的项目字段而设计。我正在使用 python 装饰器方法来实现这一点。出于某种原因,我无法解决这个问题,我得到了特定的 nameError ,我不确定它们来自哪里。 注意:人们已经确认这种方法工作得很好。

这是我在 spider.py 文件中的代码:

from scrapy.spider import Spider
from scrapy.http import Request,FormRequest
from exampleScraper.items import exampleItem
import urllib, time, MySQLdb, sys

today = time.strftime("%x %X")

class idoxpaSpider(Spider):
  pipeline = set(['insert'])

  name = 'idoxpaSpider'

  start_urls = ["http://www.example.com"]
  ###
  def parse(self, response):
    # some scrapy work 
    return item

###
class insert(object):
  def __init__(self):
    self.conn = MySQLdb.connect(<some parameters>)
    self.cursor = self.conn.cursor()

  @check_spider_pipeline
  def process_item(self, item, spider):
    return item

这就是我在管道文件中的内容:

import sys

class BoroughscrperPipeline(object):
  def process_item(self, item, spider):
    def check_spider_pipeline(process_item_method):
      @functools.wraps(process_item_method)
      def wrapper(self, item, spider):
      # message template for debugging
        msg = '%%s %s pipeline step' % (self.__class__.__name__,)

        # if class is in the spider pipeline then use use process_item normally
        if self.__class__ in spider.pipeline:
          spider.log(msg % 'executing', level=log.DEBUG)
          return process_item_method(self, item, spider)

      # otherwise return the untouched item
        else:
          spider.log(msg % 'skipping', level=log.DEBUG)
          return item
      return wrapper

这是我得到的实际错误:

File "/home/mn/workbench/boroughScrper/boroughScrper/spiders/westminsterSpider.py", line 40, in insert
    @check_spider_pipeline
NameError: name 'check_spider_pipeline' is not defined

知道这是哪里出错了吗?

【问题讨论】:

    标签: python import scrapy decorator


    【解决方案1】:

    check_spider_pipeline 是“未定义”,因为找不到它。它不在spider.py 脚本可见的范围内,而是在BoroughscrperPipeline.process_item 的局部变量中定义。您需要使其在您的范围内可见。例如检查这个答案:How can I use different pipelines for different spiders in a single Scrapy project

    【讨论】:

      猜你喜欢
      • 2015-11-07
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-10
      • 2016-07-10
      • 1970-01-01
      相关资源
      最近更新 更多