我使用csv
库来创建产品表。
为了将其导入网站,我需要将每个特征写在一个单独的列中。
使用简单循环添加新行:
writer = csv.writer(csvfile)
for product in products:
writer.writerow((product['price'],
product['vendor_code'],
product['characteristics']))
添加新的product
:
product = []
product.append({
'price' : price,
'vendor_code' : vendor_code,
'characteristics' : characteristics,
})
characteristics
- 包含每个特征作为单独元素的数组
如何以这种形式获取输出文件:
190$ #0172 characteristic1 characteristic2 characteristic3
characteristics
- 初始化:
try:
characteristics = []
soup_characteristics = soup.find_all('tr', {'class' : 'product_card__product_characters_item clearfix'})
for ch in soup_characteristics:
characteristics.append(re.sub('\s\s+|\n',' ', ch.text))
except AttributeError:
characteristics = ""
答案 0 :(得分:1)
尝试解压缩特征数组:
for product in products:
writer.writerow((product['price'],
product['vendor_code'],
*product['characteristics']))
以下是我测试的代码:
products = [{
'price': 100,
'vendor': 123,
'characters': [7, 8, 9],
}]
with open('test.csv', 'w') as fo:
writer = csv.writer(fo)
for p in products:
writer.writerow((
p['price'],
p['vendor'],
*p['characters'],
))
以下是test.csv
文件的内容:
100,123,7,8,9
答案 1 :(得分:0)
您应该能够构建一个列表作为整行写入:
for product in products:
row = [product['price'],product['vendor_code']] # [price,vendor_code]
row.extend(product['characteristics']) # [price,vendor_code,characteristic1,characteristic2,...]
writer.writerow(row) # writes each value in the list as a new column