[英]Python sqlite3, insert data from for loop
我制作了一個 web 抓取器,想將其插入數據庫。 到目前為止,我將所有內容都寫入了 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()
您正在迭代所有 collections 以打印它們的值,但不插入到數據庫中。 由於 Python 的(寬松的)范圍規則,迭代變量在迭代后仍然可用,因此您可以使用每個 scope 的最后一個值執行一次插入,僅此而已。
為了插入記錄,您需要實際創建記錄並插入它們,例如
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)
)
請注意參數替換的使用:在您的原始代碼中,如果值包含任何類型的 SQL 元字符(通常是單引號),您的查詢將中斷。 這也會讓您面臨 sql 注入問題(您正在抓取的網站實際上可以用作防御措施)。
通過使用占位符,數據庫 API 可以知道這些是“外部值”並在內部以其喜歡的方式正確處理它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.