首页 > 解决方案 > 为每个查询的列表项保存单独的 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)

标签: pythonpython-3.xcsvbeautifulsoup

解决方案


是的,你是对的,文件内容在这里被覆盖了。有很多方法可以绕过这个限制,最简单的方法是在文件名上附加一个整数值,以便于解释。

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 中调用的,它们可以帮助您将动态内容放入字符串中。


推荐阅读