python爬取当当图书信息并存到csv
时间: 2023-08-05 15:40:03 浏览: 57
好的,我可以为您提供Python爬取当当图书信息并存到CSV文件的代码示例。您可以按照以下步骤操作:
1. 安装所需库:requests、BeautifulSoup、csv
```
pip install requests
pip install beautifulsoup4
```
2. 编写代码:
```python
import requests
from bs4 import BeautifulSoup
import csv
# 设置请求头,模拟浏览器访问
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'}
# 要爬取的当当图书网址
url = 'http://search.dangdang.com/?key=python&act=input&page_index='
# 存储结果的CSV文件名
filename = 'books.csv'
# 打开CSV文件,以写入模式写入数据
with open(filename, 'w', newline='', encoding='utf-8') as csvfile:
# 设置CSV文件的列名
fieldnames = ['书名', '作者', '价格', '出版社', 'ISBN']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
# 爬取前5页数据
for i in range(1, 6):
# 构造当前页的URL
cur_url = url + str(i)
# 发送请求,获取响应
response = requests.get(cur_url, headers=headers)
# 解析HTML页面
soup = BeautifulSoup(response.text, 'html.parser')
# 获取所有图书信息
items = soup.select('.bigimg > ul > li')
# 循环遍历每一本图书,提取信息并写入CSV文件
for item in items:
title = item.select('.name > a')[0].text.strip()
author = item.select('.publisher_info')[0].text.strip().split('/')[0]
price = item.select('.price > p > span')[0].text.strip()
publisher = item.select('.publisher_info')[0].text.strip().split('/')[-3]
isbn = item.select('.publisher_info')[0].text.strip().split('/')[-1]
writer.writerow({'书名': title, '作者': author, '价格': price, '出版社': publisher, 'ISBN': isbn})
print('爬取完成!')
```
3. 运行代码,等待爬取完成。爬取完成后,您可以在当前目录下找到名为“books.csv”的CSV文件,其中包含爬取到的当当图书信息。
希望这个代码示例对您有所帮助!