0

我正在使用Scrapy将网站中的内容解析为Items,它复制了dictAPI:

import scrapy

class ScheduleItem(scrapy.Item):
    flight = scrapy.Field()

我正在尝试将上面的项目直接用作MySQLCursor.execute()使用 pyformat 样式值的连接器/Python 语句的数据。但是,它因以下错误而崩溃:

(Pdb) add_schedule_sql()
'INSERT INTO schedules (flight) VALUES (%(flight)s)'

(Pdb) foo = items.ScheduleItem();
(Pdb) foo['flight'] = 'abc'
(Pdb) foo.keys()
['flight']
(Pdb) print foo
{'flight': 'abc'}
(Pdb) self.cursor.execute(add_schedule_sql(), foo)
*** ProgrammingError: Wrong number of arguments during string formatting

有一个值要插入,而 Item 中只有一个值,两者都具有相同的键,所以我对这个错误感到困惑。(这里的源代码,这表明它实际上隐藏了一个 TypeError。)如果我使用一个普通的旧字典,它工作正常:

(Pdb) bar = {'flight': 'abc'}
(Pdb) bar.keys()
['flight']
(Pdb) self.cursor.execute(add_schedule_sql(), bar)
(Pdb)

如果我将项目映射到字典中,调用也可以正常工作:

(Pdb) self.cursor.execute(add_schedule_sql(), dict(item))
(Pdb)

以上很简单,它实际上充分解决了我的问题,但我仍然很好奇仅使用 Item 有什么问题。Python 2.7.5,Scrapy 0.24(最新稳定版)。

4

1 回答 1

1

The following works for me. So we need to see your implementation of ScheduleItem and also we need the version numbers of the libraries involved.

In [10]: class ScheduleItem(scrapy.Item):
flight = scrapy.Field()
delay = scrapy.Field()
....:     

In [11]: foo = ScheduleItem()

In [12]: foo['flight'] = 'abc'

In [13]: foo
Out[13]: {'flight': 'abc'}

In [14]: "test %(flight)s str"%(foo)
Out[14]: 'test abc str'

In [15]: "test (flight) and %(flight)s str"%(foo)
Out[15]: 'test (flight) and abc str'
于 2014-09-21T13:59:39.263 回答