python爬取网页内容并保存为csv文件
时间: 2023-09-20 08:09:14 浏览: 211
自己开发的一个python网页爬虫,模拟网页操作,爬取的内容可直接保存为为csv格式
要将爬取的网页内容保存到CSV文件中,可以使用Python中的csv模块。具体步骤如下:
1. 导入相关模块:
```python
import requests
import csv
from bs4 import BeautifulSoup
```
2. 发送HTTP请求,获取网页内容:
```python
url = 'http://www.example.com'
response = requests.get(url)
html_content = response.content
```
3. 解析HTML内容,获取需要的信息:
```python
soup = BeautifulSoup(html_content, 'html.parser')
title = soup.title.string
text = soup.get_text()
```
4. 将获取的信息写入CSV文件:
```python
with open('example.csv', 'w', encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Title', 'Text'])
writer.writerow([title, text])
```
注意事项:
- `csv.writer()`中`newline=''`参数的作用是防止写入CSV文件时出现空行;
- CSV文件的编码一般为`utf-8`,中文字符需要特别注意编码问题。
完整代码示例:
```python
import requests
import csv
from bs4 import BeautifulSoup
url = 'http://www.example.com'
response = requests.get(url)
html_content = response.content
soup = BeautifulSoup(html_content, 'html.parser')
title = soup.title.string
text = soup.get_text()
with open('example.csv', 'w', encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['Title', 'Text'])
writer.writerow([title, text])
```
执行完毕后,当前目录下会生成一个名为`example.csv`的文件,文件内容为爬取的网页标题和文本。
阅读全文