Python sqlite3, 从for循环插入数据

Python sqlite3, insert data from for loop

我制作了一个网络抓取工具,想将其插入到数据库中。 到目前为止,我将所有内容都写入了 Excel 并且工作正常。 但是现在我无法将数据插入数据库,它只是插入第一个循环的最后一条记录(carname 等)。 for 循环的所有数据都完全打印在我的屏幕上,但不在我的数据库中。

这是我的代码,谁能告诉我如何将所有数据也放入数据库中。

for cars in car_names:
    print(cars.text)

for cars2 in car_names2:
    print(cars2.text)

for price in prices:
    print(price.text)

for price2 in prices2:
    print(price2.text)

for image in images:
    print(image.get_attribute('src'))

print(carnamelist)
print(location)
print(len(images))

insert_query = f'''INSERT INTO cardata (CarName, CarModel, ImageUrl, FullPrice, Price, Location)
        VALUES ('{cars.text}', '{cars2.text}', '{image.get_attribute('src')}', '{price.text}', '{price2.text}', '{location}');
    '''
cursor.execute(insert_query)
connection.commit()

您正在迭代所有集合以打印它们的值,而不是插入到数据库中。由于 Python 的(宽松的)范围规则,迭代变量在迭代后仍然可用,因此您可以使用每个范围的最后一个值执行 one 插入,仅此而已.

为了插入记录,您需要实际创建记录并插入它们,例如

for name, name2, price, price2, image in zip(car_names, car_names2, prices, prices2, images):
    cursor.execute(
        "insert into cardata (carname, carmodel, imageurl, fullprice, price, location) values (?, ?, ?, ?, ?, ?)",
        (name.text, name2.text, image.getattribute('src'), price.text, price2.text, location)
    )

请注意 parameter substitution 的使用:在您的原始代码中,如果值包含任何类型的 SQL 元字符(通常是单引号),您的查询将会中断。这也会让您面临 sql 注入问题(您正在抓取的网站实际上可以用作防御措施)。

通过使用占位符,数据库 API 可以知道这些是“外部值”并在内部以其喜欢的方式正确处理它们。