登录
首页 >  文章 >  python教程

Python爬虫保存数据到CSV教程

时间:2025-12-25 18:37:58 242浏览 收藏

亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《Python爬虫如何保存数据到CSV文件》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。

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

Python爬虫怎样使用CSV存储数据_Python爬虫将抓取结果保存为CSV文件方法

Python爬虫抓取数据后,使用CSV格式存储是一种简单高效的方式。CSV文件可以用Excel打开,也便于导入数据库或进行数据分析。下面介绍如何在爬虫中将结果保存为CSV文件。

1. 使用内置csv模块写入数据

Python自带的csv模块非常适合处理结构化数据。适合存储表格类信息,比如商品名称、价格、链接等。

基本步骤:

  • 导入csv和open函数打开文件
  • 创建csv.writer对象
  • 写入表头(可选)
  • 逐行写入爬取的数据

示例代码:

import csv
import requests
from bs4 import BeautifulSoup
<h1>模拟请求网页</h1><p>url = "<a target='_blank'  href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq5roGCUgXuytMyero6Kn83GjHPXkraZo5qYYKbFenqqv4GOmpSBhqKu3LOifWSJ0bJ4mNuGqrluhq2Bqa-GlJ2-s4Flf32kbL-3s2uNrITfvoiHzobQsW4' rel='nofollow'>https://example.com/products</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)

2. 使用pandas更方便地导出CSV

如果你已经用pandas做数据处理,可以直接把列表或字典转成DataFrame再保存。

优点:自动处理编码、支持中文、列对齐整齐。

import pandas as pd
<h1>假设数据是字典列表</h1><p>data = [
{'Name': '手机', 'Price': '¥2999', 'Link': '<a target='_blank'  href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq5roGCUgXuytMyerpl6n5mwoX_amracsYHffZqrq36fv42JZH19i6S0t7ijgZx8mL2hft2Ht8tuh62FqrBkfa6ya41hibOTorS0o3U' rel='nofollow'>https://xxx.com/1</a>'},
{'Name': '耳机', 'Price': '¥199', 'Link': '<a target='_blank'  href='https://www.17golang.com/gourl/?redirect=MDAwMDAwMDAwML57hpSHp6VpkrqbYLx2eayza4KafaOkbLS3zqSBrJvPsa5_0Ia6sWuR4Juaq6t9nq5roGCUgXuytMyerpl6n5mwoX_amracsoHffZqrq36fv42JZH19i6S0t7ijgZx8mL2hft2Ht8tuh62FqrBkfa6ya41hibOTorS0o3U' rel='nofollow'>https://xxx.com/2</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乱码。

3. 处理异常与确保文件安全关闭

网络爬虫可能遇到请求失败、数据缺失等问题,需做好容错。

  • 使用try-except捕获异常
  • 始终用with语句操作文件,确保自动关闭
  • 检查字段是否存在再写入,防止报错

例如:

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更适合后续分析。根据需求选择方法就行。

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于文章的相关知识,也可关注golang学习网公众号。

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>