ConfigParser 和 Scrapy:NoSectionError

ConfigParser and Scrapy: NoSectionError

我的 Scrapy 爬虫在启动时出现问题。

我使用 ConfigParser 是为了有一个小的 config.ini 来设置我的 table 名称,这是我每次启动要废弃的爬虫时创建的。这是一种基本的报废方法,但我仍然对 scrapy 和 python

很陌生

我收到以下错误:

File "c:\python27\lib\ConfigParser.py", line 279, in options
    raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'SectionOne'
2016-02-04 15:10:57 [twisted] CRITICAL:

这是我的 config.py:

import ConfigParser 
import os

Config = ConfigParser.ConfigParser()
Config.read(os.getcwd() + '/config.ini')

def ConfigSectionMap(section):
    dict1 = {}
    options = Config.options(section)
    for option in options:
        try:
           dict1[option] = Config.get(section, option)
           if dict1[option] == -1:
               DebugPrint("skip: %s" % option)
        except:
            print("exception on %s!" % option)
            dict1[option] = None
    return dict1

这是我的 config.ini

[SectionOne]
nom_table: Seche_cheveux

这是我的 pipeline.py:

import sqlite3
from datetime import date, datetime
import os
from config import *

TableName = ConfigSectionMap("SectionOne")['nom_table']
print TableName


class  sqlite3Pipeline(object):

    def __init__(self):
        #initialisation de la base et connexion
        try:
            #self.setupDBCon()
            self.con = sqlite3.connect(os.getcwd() + '/db.sqlite')
            self.cur = self.con.cursor()
            self.table_name = TableName
            self.createTables()
        except sqlite3.Error as e:
            raise e


    def createTables(self):
        self.createMgTable()

    def closeDB(self):
        self.con.close()

    def __del__(self):
        self.closeDB()

    def createMgTable(self, table_name):
        self.cur.execute("CREATE TABLE IF NOT EXISTS" + table_name + "(\
        nom TEXT UNIQUE, \
        url TEXT UNIQUE, \
        prix TEXT, \
        stock TEXT, \
        revendeur TEXT, \
        livraison TEXT, \
        img TEXT UNIQUE, \
        detail TEXT UNIQUE, \
        bullet TEXT UNIQUE, \
        created_at DATE \
        )")

    def process_item(self, item, spider):
        self.storeInDb(item)
        return item

    def storeInDb(self,item):
       etc....
       etc...

你能告诉我如何用 scrapy 爬虫处理 configparser 吗?如果可能的话告诉我我做错了什么

有关信息,当我分别启动每个文件时,我包含的所有打印功能都运行良好。

当找不到配置文件时,

ConfigParser.read() 往往会自动失败。当前工作目录 (os.getcwd()) 可能发生了变化,导致它无法找到 config.ini.

如果您的 config.ini 文件在您的 config.py 旁边,您可以改用它:

Config.read(os.path.join(os.path.dirname(__file__), 'config.ini'))