2
我已經使用這裏描述的方法之一Python write to CSV line by line試圖將我的輸出的所有行寫入.CSV。我已經設法達到輸出和生成CSV的階段,但不是顯示我的數據的所有行,我看到一行,重複4次,沒有別的。Python CSV導出4個相同的行
任何人都可以看到這裏的問題是什麼?
from bs4 import BeautifulSoup
import requests
import csv
headers = {'User-Agent': 'Mozilla/5.0'}
for i in range(1, 300):
url = "xxx?page=%s" % i
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
items = soup.find_all('div', class_='product-block__info')
for item in items:
product = item.find('span', class_='short_desc').text
stock = item.find('span', class_='count_product_stock hidden').text
brand = item.find('h4', class_='brand').text
price = item.find('span', class_='selling_price').text
# create a list of all the fields
sheets = [brand, product, stock, price]
print(sheets)
with open('csvfile.csv','wt') as file:
for l in sheets:
file.writelines(sheets)
file.write('\n')
在for循環中添加一個打印線,寫出線條,你會發現它。也意識到每次打開它時文件都會被截斷。 –
我已經打印出行,但它仍然不清楚發生了什麼事情,以獲得.csv結果? –
'sheets'是一條線。 '對於表單中的l:'遍歷行中的項目,但'l'從不使用。 'file.writelines'對於單行不正確。 'file.write('\ n')'不需要。 'csv'將管理這些行。你不知道你爲什麼沒有在你的csv中得到任何逗號嗎? –