1. 程式人生 > >Scrapy爬蟲(5)爬取噹噹網圖書暢銷榜

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

  開啟dangdang.csv,其中的部分內容如下:


書的資訊

  我們可以發現,書的資訊不是有序儲存的,但還是達到了筆者的要求,怎麼樣,是不是覺得Scrapy簡單又使用呢?強大的Scrapy!