python爬虫数据写入csv
时间: 2023-07-17 12:08:46 浏览: 113
你可以使用Python的爬虫库(如BeautifulSoup、Scrapy等)来抓取网页数据,并使用csv库将数据写入CSV文件。下面是一个简单的示例代码:
```python
import requests
import csv
# 发起HTTP请求,获取网页内容
response = requests.get('http://example.com')
# 解析网页内容
# 这里使用BeautifulSoup作为示例,你也可以使用其他库或自己编写解析逻辑
from bs4 import BeautifulSoup
soup = BeautifulSoup(response.text, 'html.parser')
# 提取需要的数据
data = []
# 假设需要提取标题和链接
for item in soup.find_all('a'):
title = item.text
link = item.get('href')
data.append([title, link])
# 将数据写入CSV文件
with open('data.csv', 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile)
# 写入表头
writer.writerow(['Title', 'Link'])
# 写入数据
writer.writerows(data)
print('数据写入完成!')
```
这个示例代码使用requests库发起HTTP请求,获取网页内容。然后使用BeautifulSoup解析网页内容,提取需要的数据(这里假设需要提取标题和链接)。最后使用csv库将数据写入名为data.csv的CSV文件。记得将代码中的URL和需要提取的数据字段根据实际情况进行修改。
阅读全文
相关推荐

















