import csv
from lxml import etree
import requests
fp=open('C:\\Users\我的电脑\Desktop\doubanbook.csv','wt',newline='',encoding='utf-8')
writer=csv.writer(fp) #创建csv
writer.writerow(('name','url','author','publisher','date','price','rate','comment')) #在csv文件中写下这一行
urls=['https://book.douban.com/top250?start={}'.format(str(i) for i in range(0,250,25))] #构造链接
headers={
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
for url in urls:
html=requests.get(url,headers=headers)
selector=etree.HTML(html.text) #解析获得的html文件
infos=selector.xpath('//tr[@class="item"]') #//标签[@class=名称] 用来锁定标签
for info in infos: #xpth用的是先大后小原则,即先得到相对上级的tr,再得到后续的标签
name=info.xpath('td/div/a/@title')[0]
url=info.xpath('td/div/a/@href')[0]
book_infos=info.xpath('td/p/text()')[0]
author=book_infos.split('/')[0]
publisher=book_infos.split('/')[-3]
date=book_infos.split('/')[-2]
price=book_infos.split('/')[-1]
rate=info.xpath('td/div/span[2]/text()')[0]
comments=info.xpath('td/p/span/text()') #text()转换为text形式
comment=comments[0] if len(comments) != 0 else "空" #判断评论是否为空
writer.writerow((name,url,author,publisher,date,price,rate,comment))
fp.close()
爬取的网址 https://book.douban.com/top250?start=25