写一个豆瓣图书top250数据采集的代码
时间: 2023-12-01 18:28:02 浏览: 34
好的,以下是一个使用Python的豆瓣图书top250数据采集的代码示例:
```python
import requests
from bs4 import BeautifulSoup
# 设置请求头,模拟浏览器请求
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.36'}
# 请求url
url = 'https://book.douban.com/top250'
# 发送请求并获取响应
response = requests.get(url, headers=headers)
# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
# 获取书籍列表
book_list = soup.find('div', class_='article').find_all('tr', class_='item')
# 遍历书籍列表并保存相关信息
for book in book_list:
# 获取书名
title = book.find('div', class_='pl2').find('a')['title']
# 获取评分
rating = book.find('div', class_='star').find('span', class_='rating_nums').get_text()
# 获取评价人数
rating_num = book.find('div', class_='star').find('span', class_='pl').get_text().strip('(').strip(')').strip('人评价')
# 获取作者、出版社、出版日期、价格等信息
info = book.find('p', class_='pl').get_text().split('/')
author = info[0].strip()
publisher = info[-3].strip()
date = info[-2].strip()
price = info[-1].strip()
# 打印书籍信息
print('书名:', title)
print('评分:', rating)
print('评价人数:', rating_num)
print('作者:', author)
print('出版社:', publisher)
print('出版日期:', date)
print('价格:', price)
print('----------------------')
```
这个代码会爬取豆瓣图书top250的书籍信息,包括书名、评分、评价人数、作者、出版社、出版日期、价格等信息,并逐个打印输出。你可以根据自己的需求对代码进行修改和扩展。需要注意的是,爬取网站内容时需要尊重网站的robots.txt协议,避免对网站造成不必要的负担。