码迷,mamicode.com
首页 > 其他好文 > 详细

爬取豆瓣热销书榜前250 生成.csv文件

时间:2018-07-03 21:38:43      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:most   问题解决   traceback   rac   writer   str   row   tree   tle   

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是什么

爬取豆瓣热销书榜前250 生成.csv文件

标签:most   问题解决   traceback   rac   writer   str   row   tree   tle   

原文地址:https://www.cnblogs.com/zhentaoFrezt/p/9260444.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!