Python 如何将For循环数据写入CSV文件
我正在构建一个机器人,它可以从ebay上获取产品的价格,并将所有信息写入csv文件。但当它使用for循环将信息输入到csv文件时,我遇到了麻烦。如何将所有for循环数据写入csv文件。由于for循环,代码只写入最后一个产品的信息Python 如何将For循环数据写入CSV文件,python,web-scraping,beautifulsoup,export-to-csv,ebay-api,Python,Web Scraping,Beautifulsoup,Export To Csv,Ebay Api,我正在构建一个机器人,它可以从ebay上获取产品的价格,并将所有信息写入csv文件。但当它使用for循环将信息输入到csv文件时,我遇到了麻烦。如何将所有for循环数据写入csv文件。由于for循环,代码只写入最后一个产品的信息 headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'} s
headers = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36'}
searchterm = "Laptops"
url = f'https://www.ebay.com/sch/i.html?_from=R40&_nkw={searchterm}&_sacat=0&LH_PrefLoc=1&LH_Auction=1&rt=nc&LH_Sold=1&LH_Complete=1'
response = requests.get(url,headers=headers)
soup = BeautifulSoup(response.content,'html.parser')
for item in soup.select('.s-item'):
print(len(soup.select('.s-item')))
try:
print(item.select('.s-item__title')[0].get_text())
print(item.select('.s-item__subtitle')[0].get_text())
print(item.select('.s-item__price')[0].get_text())
print(item.select('.s-item__location')[0].get_text())
print(item.select('.s-item__shipping')[0].get_text())
print("\n\n\n----------------------------------------------")
with open('Products.csv', mode='w') as file_in:
writers = csv.writer(writers)
employee_writer.writerow(['Product', 'Price'])
employee_writer.writerow(['', ''])
employee_writer.writerow([item.select('.s-item__title')[0].get_text(),item.select('.s-item__price')[0].get_text()])
except Exception as e:
print("ERROR!")
我希望表看起来像构造代码,以便在循环之外打开文件:
with open('Products.csv', mode='w') as file_in:
writers = csv.writer(writers)
for item in soup.select('.s-item'):
# etc...
所发生的事情是,循环的每次迭代都会打开文件,并使用mode='w'
覆盖文件内容