gpt4 book ai didi

python - Scrapy管道查询并非所有在字符串格式化期间转换的参数

转载 作者:行者123 更新时间:2023-12-01 08:55:11 24 4
gpt4 key购买 nike

你好,我正在尝试使用 scrapy 插入 postgresql。

我正在尝试使用 1 个蜘蛛将数据插入到 1 个数据库的多个列中

插入 1 个表的代码有效,但是当我更改数据库时,需要插入多个表。

我重写了管道查询的代码,现在当我尝试运行我的蜘蛛时,它返回“并非所有参数在字符串格式化期间都已转换”

我知道我的查询在 python 中使用“%s”有问题,但我不知道如何解决或更改查询。

这是我的 pipelines.py:

import psycopg2
class TutorialPipeline(object):
def open_spider(self, spider):
hostname = 'localhost'
username = 'postgres'
password = '123' # your password
database = 'discount'
self.connection = psycopg2.connect(host=hostname, user=username, password=password, dbname=database)
self.cur = self.connection.cursor()

def close_spider(self, spider):
self.cur.close()
self.connection.close()

def process_item(self, item, spider):
self.cur.execute("insert into discount(product_name,product_price,product_old_price,product_link,product_image) values(%s,%s,%s,%s,%s)",(item['product_name'],item['product_price'],item['product_old_price'],item['product_link'],item['product_image']))
self.cur.execute("insert into categories(name) values(%s)",(item['category_name']))
self.cur.execute("insert into website(site) values(%s)",(item['product_site']))
self.connection.commit()
return item

编辑:这里是回溯错误

self.cur.execute("insert into categories(name) values(%s)",(item['category_name'])) TypeError: not all arguments converted during string formatting

最佳答案

使用命名参数。简化示例:

def process_item(self, item, spider):
self.cur.execute('''
insert into discount(product_name, product_price)
values(%(product_name)s, %(product_price)s)''',
item)
self.cur.execute('''
insert into categories(name)
values(%(category_name)s)''',
item)
self.cur.execute('''
insert into website(site)
values(%(product_site)s)''',
item)
self.connection.commit()
return item

了解更多关于 Passing parameters to SQL queries.

关于python - Scrapy管道查询并非所有在字符串格式化期间转换的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52812602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com