答案:Python爬虫可用csv模块或pandas将数据保存为CSV文件。1. 使用csv模块可写入表头和数据,适合结构化信息存储;2. pandas能自动处理编码与中文,导出更便捷;3. 需用try-except处理异常,with确保文件安全关闭。

Python爬虫抓取数据后,使用CSV格式存储是一种简单高效的方式。CSV文件可以用Excel打开,也便于导入数据库或进行数据分析。下面介绍如何在爬虫中将结果保存为CSV文件。
Python自带的csv模块非常适合处理结构化数据。适合存储表格类信息,比如商品名称、价格、链接等。
基本步骤:
示例代码:
立即学习“Python免费学习笔记(深入)”;
import csv
import requests
from bs4 import BeautifulSoup
<h1>模拟请求网页</h1><p>url = "<a href="https://www.php.cn/link/ebae6bc5deeca109d899c4ec7d9d30c0">https://www.php.cn/link/ebae6bc5deeca109d899c4ec7d9d30c0</a>"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')</p><h1>提取数据(示例)</h1><p>products = []
for item in soup.find<em>all('div', class</em>='product'):
name = item.find('h2').text.strip()
price = item.find('span', class_='price').text.strip()
link = item.find('a')['href']
products.append([name, price, link])</p><h1>写入CSV文件</h1><p>with open('products.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)</p><h1>写入标题</h1><pre class='brush:python;toolbar:false;'>writer.writerow(['Name', 'Price', 'Link'])
# 写入每条数据
writer.writerows(products)如果你已经用pandas做数据处理,可以直接把列表或字典转成DataFrame再保存。
优点:自动处理编码、支持中文、列对齐整齐。
import pandas as pd
<h1>假设数据是字典列表</h1><p>data = [
{'Name': '手机', 'Price': '¥2999', 'Link': '<a href="https://www.php.cn/link/3688bc5db453523746c83fbedd11a267">https://www.php.cn/link/3688bc5db453523746c83fbedd11a267</a>'},
{'Name': '耳机', 'Price': '¥199', 'Link': '<a href="https://www.php.cn/link/3cd9fd588c126cc9043850408c2c19ab">https://www.php.cn/link/3cd9fd588c126cc9043850408c2c19ab</a>'}
]</p><h1>转为DataFrame并保存</h1><p>df = pd.DataFrame(data)
df.to_csv('products_pandas.csv', index=False, encoding='utf-8-sig')</p>注意:保存中文时建议用utf-8-sig编码,避免Excel乱码。
网络爬虫可能遇到请求失败、数据缺失等问题,需做好容错。
例如:
try:
with open('data.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerow(['Title', 'URL'])
for item in items:
title = item.get('title', '未知')
url = item.get('url', '')
writer.writerow([title, url])
except Exception as e:
print(f"保存文件出错: {e}")
基本上就这些。用csv模块适合轻量级项目,pandas更适合后续分析。根据需求选择方法就行。
以上就是Python爬虫怎样使用CSV存储数据_Python爬虫将抓取结果保存为CSV文件方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号