ここではPython write to CSV line by lineに記載されている方法のいずれかを使用して、出力のすべての行を.CSVに書き込もうとしました。私はそれをCSVの出力と生成の段階に持っていきましたが、私のデータのすべての行を表示するのではなく、4回繰り返された1行を見ています。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'は1行です。 'for l sheets:'は行中の項目を繰り返しますが、 'l'は決して使用されません。 'file.writelines'は1行では正しくありません。 'file.write( '\ n')'は必要ありません。 'csv'は行を管理します。なぜあなたはあなたのCSVでコンマを取得していないのだろうか? –