1. 程式人生 > >利用scrapy框架實現一個簡單的爬蟲專案

利用scrapy框架實現一個簡單的爬蟲專案

首先簡單介紹一下什麼是scrapy框架?具體詳情見百科!!!

總之,scrapy是一個用於python開發抓取網站網頁的框架,更加通俗的講就是爬蟲框架!!!

下面就是利用scrapy爬取web的一個小專案:

import scrapy

class BooksSpider(scrapy.Spider):
    name = 'books'
    allowed_domains = ['books.toscrape.com']
    start_urls = ['http://books.toscrape.com/']

    def parse(self, response):

        # 1.提取資料
        for sel in response.css('article.product_pod'):
            #獲取書名
            name  = sel.xpath('//h3/a[@title]/text()').extract_first()
            #獲取書的價格
            price = sel.css(' p.price_color::text').extract_first()
            #獲取書的評分  這裡使用到正則匹配標籤屬性中的評分
            rating = sel.css('p.star-rating').re_first('star-rating (\w+)')

            #把屬性封裝入字典中
            book = {
                'name':name,
                'price':price,
                'rating':rating,
            }

            yield book

        # 2.提取連結,產生新的請求
        #提取下一頁的連結
        next_page = response.css('ul.pager li.next a::attr(href)').extract_first()

        #判斷下一頁是否存在
        if next_page:
            """
            這裡注意urljoin()函式的用法,從相對路徑獲得絕對路徑
            from urlparse import urljoin
           輸入: urljoin("http://www.asite.com/folder/currentpage.html", "anotherpage.html")
           輸出:'http://www.asite.com/folder/anotherpage.html'
            """
            next_page = response.urljoin(next_page)
            request = scrapy.Request(next_page,callback=self.parse)
            yield request

注意:

1.在終端執行時,輸入scrapy crawl books -o books.csv 執行會把獲取的結果儲存在books.csv檔案中。

2.其中使用到了urljoin函式的用法。

3.yield的用法。