python - 为每个查询的列表项保存单独的 CSV
问题描述
我是 Python 新手,正在研究一个包含网站列表的网络抓取脚本,每次脚本从列表中查询一个网站时,我都需要将其保存到单独的 CSV 文件中。
目前,它似乎迭代了我列表中的每个站点,但只保存到 CSV,即最后一个查询 ( www.website.com/3
) 中的项目。我意识到一旦它遍历我的records
列表,它就会被重置,但它不应该先保存 CSV 吗?除非文件只是被新数据覆盖,但如果是这种情况,我如何增加每个查询的文件名?
from typing import Counter
import requests
from bs4 import BeautifulSoup
import sys
import csv
pages = [
'https://www.website.com/1',
'https://www.website.com/2',
'https://www.website.com/3'
]
for page in pages:
r = requests.get(page)
soup = BeautifulSoup(r.content, 'lxml')
productName = soup.find_all('div',class_='name')
productID = soup.find_all('span', id='product_id')
productCost = soup.find_all('span', class_='regular-price')
records=[]
for item in range(len(productName)):
records.append({
'name': productName[item].find('a').text.strip(),
'product_ID': productID[item].text.strip(),
'price': float(productCost[item].text.strip()[1:].replace(",",""))
})
with open("filename.csv", 'w', newline='') as outfile:
writer = csv.DictWriter(outfile, fieldnames=records[0].keys())
writer.writeheader()
for record in records:
writer.writerow(record)
解决方案
是的,你是对的,文件内容在这里被覆盖了。有很多方法可以绕过这个限制,最简单的方法是在文件名上附加一个整数值,以便于解释。
file_name = f'filename-{value}.csv'
with open(file_name, 'w', newline='') as outfile:
... your write logic goes here ...
...
value = value + 1
value
您可以将顶部的变量初始化为0 ( value = 0
)。我在创建 file_name 变量时使用的东西是f-strings
在 python 中调用的,它们可以帮助您将动态内容放入字符串中。
推荐阅读
- python - 绘制带有掩码值的数据时,Streamplot 失败
- javascript - 如何使用 NodeJS 更新 JSON 中的特定值并将其存储回变量中
- amazon-web-services - 更改 AWS Glue Pyspark 中的分隔符
- jenkins - Jenkins 管道:分阶段运行所有步骤,即使第一个步骤失败
- python - 如何在 pythonanywhere.com 虚拟环境中更新 wkhtmltopdf 版本?
- java - Spring Data JPA检查记录是否存在并更新否则插入
- android - RecyclerView Kotlin 中的 LayoutManeger NullPointerException
- c# - SignalR向同一用户发送重复消息n次n是连接的用户数.NetCore
- javascript - MongoDB如何进入文件
- authentication - 无需重定向到登录页面的第一方(主)应用程序的 OpenID/OAuth2.0 替代方案?