爬取豆瓣热销书榜前250 生成.csv文件
from lxml import etree
import requests
import csv
fp = open('E:/doubanbook.csv','wt',newline='',encoding='utf-8')
writer = csv.writer(fp)
writer.writerow(('name','url','author','publisher','date','price','rate','comment'))
urls = ['http://book.douban.com/top250?start={}'.format(str(i)) for i in range(0,250,25)]
headers = {
'User-Agent':'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)'
}
for url in urls:
html = requests.get(url,headers=headers)
selector = etree.HTML(html.text)
infos = selector.xpath('//tr[@class="item"]')
for info in infos:
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()')
comment = comments[0] if len(comments) != 0 else "空"
writer.writerow((name,url,author,publisher,date,price,rate,comment))
fp.close()
问题:只爬取了前25的 页码无问题
问题描述:
Traceback (most recent call last):
File "C:/Users/Dell/PycharmProjects/test/test/__init__.py", line 26, in <module>
writer.writerow((name,url,author,publisher,date,price,rate,comment))
ValueError: I/O operation on closed file.
问题解决:fp.close()应该缩进到最前面 缩进问题很重要 正在了解SCV是什么