使用 Python 爬虫保存数据到 CSV 文件的基本步骤如下:
导入 `csv` 模块
import csv
定义文件名和路径
filename = "data.csv"
filepath = "/path/to/your/directory/"
打开文件并创建
with open(filepath + filename, mode="w", newline='') as csvfile:
设置列名 (如果需要):fieldnames = ['列名1', '列名2', '列名3', ...]
fieldnames = ['列名1', '列名2', '列名3', ...]
写入标题行(如果需要):
csvfile.write(','.join(fieldnames) + '\n')
循环遍历数据行并写入
```python
for row in data:
csvfile.write(','.join(str(item) for item in row) + '\n')
```
关闭文件(如果需要):
csvfile.close()
这是一个简单的示例,展示了如何将爬取的数据保存到 CSV 文件中:
import requests
from bs4 import BeautifulSoup
import csv
爬取网页
url = 'https://example.com/data.html'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
假设我们要提取的数据在表格中
table = soup.find('table')
rows = table.find_all('tr')
获取列名
headers = [header.text.strip() for header in rows.find_all('th')]
获取数据行
data = []
for row in rows[1:]:
cols = row.find_all('td')
cols = [ele.text.strip() for ele in cols]
data.append([ele for ele in cols if ele]) 去除空值
保存到 CSV 文件
with open('data.csv', mode='w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(headers)
writer.writerows(data)
请根据你的具体需求调整上述代码。如果你使用的是 Scrapy 框架,你也可以使用命令行方式保存数据到 CSV 文件,例如:
scrapy crawl your_spider_name -o output_file.csv
希望这能帮助你保存爬取的数据到 CSV 文件中