存入csv
import csv
from config.globalparameter import execl_save import csv title = '这是一个标题' price = 23.45 deal = 5 location = '广东 广州' province = '广东' city = '广州' shop = '门店' result = 1 # 构建商品信息字典 product = { 'title': title, 'price': price, 'deal': deal, 'location': location, 'province': province, 'city': city, 'shop': shop, 'isPostFree': result } print(product) # 指定要写入CSV的字段 fields = ['title', 'price', 'deal', 'location', 'province', 'city', 'shop', 'isPostFree'] # 指定CSV文件的路径 filename = execl_save # 字典写入CSV文件 with open(filename, 'w', newline='') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=fields) writer.writeheader() writer.writerow(product)
存入mysql
pip3 install pymysql pip3 install pyquery
导入
from pyquery import PyQuery as pq
数据库连接情况(数据库的表和字段要先建好)
# 数据库中要插入的表 MYSQL_TABLE = 'goods' # MySQL 数据库连接配置,根据自己的本地数据库修改 db_config = { 'host': 'localhost', 'port': 3306, 'user': 'root', 'password': 'm*******', 'database': 'may2024', 'charset': 'utf8mb4', } # 创建 MySQL 连接对象 conn = pymysql.connect(**db_config) cursor = conn.cursor()
# 构建商品信息字典 product = { 'title': title, 'price': price, 'deal': deal, 'location': location, 'province': province, 'city': city, 'shop': shop, 'isPostFree': result } try: sql = "INSERT INTO {}(price, deal, title, shop, location, province, city, isPostFree) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)".format(MYSQL_TABLE) print("sql语句为: " + sql) cursor.execute(sql, (product['price'], product['deal'], product['title'], product['shop'], product['location'], product['province'], product['city'], product['isPostFree'])) conn.commit() # cursor.close() # conn.close() print('存储到MySQL成功: ', product) except Exception as e: print('存储到MYsql出错: ', product, e)
标签:shop,city,product,deal,title,python,location,csv,字典 From: https://www.cnblogs.com/may18/p/18060866