Scrapy爬虫(5)爬取当当网图书畅销榜

  本次将会使用Scrapy来爬取当当网的图书畅销榜,其网页截图如下:

当当网图书畅销榜

  我们的爬虫将会把每本书的排名,书名,作者,出版社,价格以及评论数爬取出来,并保存为csv格式的文件。项目的具体创建就不再多讲,可以参考上一篇博客,我们只需要修改items.py文件,以及新建一个爬虫文件BookSpider.py.
  items.py文件的代码如下,用来储存每本书的排名,书名,作者,出版社,价格以及评论数。

import scrapy

class BookspiderItem(scrapy.Item):
    rank = scrapy.Field()
    name = scrapy.Field()
    author = scrapy.Field()
    press = scrapy.Field()
    price = scrapy.Field()
    comments = scrapy.Field()

  BookSpider.py代码如下,用来具体地爬取数据。

import scrapy
from scrapy.selector import Selector
from bookSpider.items import BookspiderItem

class bookSpider(scrapy.Spider):
    name = 'bookScrapy'
    start_urls = ['http://bang.dangdang.com/books/bestsellers/01.00.00.00.00.00-recent7-0-0-1-%d'%i for i in range(1,26)]

    def parse(self, response):
        item = BookspiderItem()
        sel = Selector(response)
 
        book_list = response.css('ul.bang_list.clearfix.bang_list_mode').xpath('li')
 
        for book in book_list:
            item['rank'] = book.css('div.list_num').xpath('text()').extract_first()
            item['name'] = book.css('div.name').xpath('a/text()').extract_first()
            item['author'] = book.css('div.publisher_info')[0].xpath('a/text()').extract_first()
            item['press'] = book.css('div.publisher_info')[1].xpath('a/text()').extract_first()
            item['price'] = book.css('span.price_n').xpath('text()').extract_first()
            item['comments'] = book.css('div.star').xpath('a/text()').extract_first()
            
            yield item

  代码就是这么简单,哈哈,别忘了在settings.py中将设置“ROBOTSTXT_OBEY = False”.
  整个项目就是这样啦,最后,我们运行命令

scrapy crawl bookScrapy -o dangdang.csv -t csv

这样就会把刚才爬取的数据保存为dangdang.csv,该文件在spiders目录下。

  打开dangdang.csv,其中的部分内容如下:

  我们可以发现,书的信息不是有序储存的,但还是达到了笔者的要求,怎么样,是不是觉得Scrapy简单又使用呢?强大的Scrapy!

注意:本人现已开通两个微信公众号: 因为Python(微信号为:python_math)以及轻松学会Python爬虫(微信号为:easy_web_scrape), 欢迎大家关注哦~~

原文地址:https://www.cnblogs.com/jclian91/p/9172385.html