练习---将爬取的豆瓣TOP250书籍存储到csv文件中

之前有写过用xlwt存储到excel表中,这次写存储到csv文件中

import requests
import json
import csv
from bs4 import BeautifulSoup

books=[]

def book_name(url):
	res=requests.get(url)
	html=res.text
	soup=BeautifulSoup(html,'html.parser')
	items=soup.find(class_="grid-16-8 clearfix").find(class_="indent").find_all('table')
	
	for i in items:	
		book=[]   
		title=i.find(class_="pl2").find('a')
		book.append('《'+title.text.replace(' ','').replace('\n','')+'》')
		
		star=i.find(class_="star clearfix").find(class_="rating_nums")
		book.append(star.text+'分')
		
		try:
			brief=i.find(class_="quote").find(class_="inq")
		except AttributeError:
			book.append('”暂无简介“')
		else:
			book.append(brief.text)
			
		link=i.find(class_="
爬取豆瓣读书Top250的数据并保存到CSV和XLS(Excel)文件通常涉及以下几个步骤: 1. **获取数据**: 使用网络爬虫库,如Python的`requests`和`BeautifulSoup`(针对HTML页面)、`Scrapy`(更强大的爬虫框架)或者`selenium`(模拟浏览器),访问豆瓣读书Top250的网页(https://book.douban.com/top250)。 2. **解析数据**: 解析网页内容,提取书名、作者、评分和简介等信息。这通常需要定位到相关的HTML元素,并通过CSS选择器或XPath表达式找到。 3. **数据处理**: 将抓取的数据存储到字典列表中,每个字典代表一条书籍记录,方便后续操作。 4. **保存到文件**: 使用Python内置的`csv`模块将数据保存为CSV文件,每行对应一条记录。对于XLS文件,可以使用第三方库`pandas`,它提供了直接写入Excel的功能。 ```python import requests from bs4 import BeautifulSoup import csv import pandas as pd # 第一步:发送请求并解析HTML url = "https://book.douban.com/top250" response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') # 第二步:查找并提取数据 books_data = [] rows = soup.select('.subject-item') for row in rows: title = row.select_one('.title a').text.strip() author = row.select_one('.author').text.strip() or "-" rating = float(row.select_one('.rating_num').text) intro = row.select_one('.inq').text.strip() or "-" books_data.append({'书名': title, '作者': author, '评分': rating, '简介': intro}) # 第三步:保存数据 with open('top250_books.csv', 'w', newline='', encoding='utf-8') as csvfile: writer = csv.DictWriter(csvfile, fieldnames=books_data[0].keys()) writer.writeheader() writer.writerows(books_data) df_books = pd.DataFrame(books_data) df_books.to_excel('top250_books.xls', index=False) # 对于XLS文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值