1. 程式人生 > >爬蟲:Python3.6 + Scrapy 框架的案例

爬蟲:Python3.6 + Scrapy 框架的案例

爬蟲框架學習scrapy

Demo1

在爬蟲專案的檔案下面 cmd 進入到專案資料夾

Scrapy startproject test01

在利用pychrom開啟建立的test01專案

專案組織架構如下圖

Scrapy.cfg 專案的配置檔案

Test01/: 表示該專案的paython模組

Test01/spiders: 放置spider的程式碼目錄,用於如何爬取某個(或者某些)網站, 包括了爬取的動作(例如是否跟進連線)以及如何從網頁的內容中提取結構化的資料

Test01/items.py: 專案中的item檔案,用於爬取的資料結構的定義,且儲存資料的容器

Test01/pipelines.py: 專案中的pipelines檔案,用於處理資料的過程,例如清理,去重,驗證,儲存等、。

Test01/settings.py:專案中的設定檔案,用於提供定製的scrapy元件,可以控制包括核心core, 外掛(extension)pipeline spider

1、刪除原來框架預設的item.py的檔案

我們自定義自己的檔案CourseItems.py

import scrapy

 

 

class CourseItems(scrapy.Item):

    # 課程標題

    title = scrapy.Field()

    # 課程url

    url = scrapy.Field()

    # 課程標題圖片

    image_url = scrapy.Field()

    # 課程描述

    introduction = scrapy.Field()

    # 訪問課程人數

    student_num = scrapy.Field()

2、在spider目錄下面,建立自己的爬取類MySpider.py 用於爬取網站中的課程的資訊

 

import scrapy

from test01.CourseItems import CourseItems

 

 

class MySpider(scrapy.Spider):

    # 用於區別spider

    name = 'MySpider'

    # 允許訪問的域

    allowed_domain = ['imooc.com']

    # 爬取的網址

    start_urls = ['http://www.imooc.com/course/list']

 

    # 爬取的方法

    def parse(self, response):

        # 例項化一個容器儲存爬取的資訊

        item = CourseItems()

        # 這部分是需要我們爬取的資訊 利用xpath 來選擇需要的資訊 具體是根據網頁的html標籤來進行判斷

        # 先獲取每一個課程的div

        for box in response.xpath('//div[@class="course-card-container"]/a[@target="_blank"]'):

            # 獲取濃眉哥div課程的路徑

            item['url'] = 'http://www.imooc.com' + box.xpath('.//@href').extract()[0]

            # 偶去div裡面的課程標題

            item['title'] = box.xpath('.//div[@class="course-card-content"]/h3/text()').extract()[0].strip()

            # 獲取課題圖片的地址

            item['image_url'] = 'http:' + box.xpath('.//@src').extract()[0]

            # 獲取div中的學生人數

            item['student_num'] = box.xpath('.//span/text()').extract()[0].strip()[:-3]

            # 獲取div中的課程簡介

            item['introduction'] = box.xpath('.//p/text()').extract()[0].strip()

            # 返回資訊

            yield item

 

3、刪除原來預設的pipeline.py的檔案

建立自己的檔案,儲存資料為json格式

 

class MyPipeline(object):

    # def __init__(self):

    #     self.file = open('data.json', 'wb', encoding='utf-8')

    #

    # def process_item(self, item, spider):

    #     # 讀取item裡面的資料

    #     line = json.dumps(dict(item), ensure_ascii=False) + "\n"

    #     # 寫入檔案

    #     self.file.write(line)

    #     # 返回item

    #     return item

    #

    # # 該方法在spider被啟動的時候呼叫

    # def open_spider(self):

    #     pass

    #

    # # 該方法在spider被關閉的時候呼叫

    # def close_spider(self):

    #     pass

 

    """

    這裡在按照上面的方式在進行操作的時候發現會報錯區的 所以 不要在init方法,裡面去操作

    """

 

    def open_spider(self, spider):

        self.file = codecs.open('data.json', 'wb', encoding='utf-8')

 

    def close_spider(self, spider):

        # self.file.close()

        pass

 

    def process_item(self, item, spider):

        line = json.dumps(dict(item), ensure_ascii=False) + "\n"

        self.file.write(line)

        return item

 

4、重新定義資料處理類

把圖片的url進行下載,並存儲到指定的目錄下面

 

# encoding=utf-8

import scrapy

from scrapy.contrib.pipeline.images import ImagesPipeline

from scrapy.exceptions import DropItem

 

 

class ImgPipeline(ImagesPipeline):

    # 通過抓取的圖片url獲取一個Request用於下載

    def get_media_requests(self, item, info):

        # 返回Request根據圖片圖片url下載

        yield scrapy.Request(item['image_url'])

 

    # 當下載請求完成後執行該方法

    def item_completed(self, results, item, info):

        # 獲取下載地址

        image_path = [x['path'] for ok, x in results if ok]

        # 判斷是否成功

        if not image_path:

            raise DropItem("Item contains no images")

        # 將地址存入item

        item['image_path'] = image_path

        return item

 

5、修改settings.py檔案

最後在settings.py裡面新增ITEM_PIPELINES新增爬取資料處理類的路徑 以及執行順序,新增IMAGE_STORE 圖片下載的儲存路徑

ITEM_PIPELINES = {

    'test01.MyPipeline.MyPipeline': 100,

    'test01.ImagePipeline.ImgPipeline': 1,

}

 

IMAGES_STORE = 'd:\\img'

 

6、執行命令開啟爬取之旅

Scarpy crawl MySpider

 

7、檢視結果資料檔案  

在專案下面產生的data.json 檔案 該檔案是在Mypipeline.py裡面設定的 ,在專案檔案下面的位置看下圖所示:

 

{"url": "http://www.imooc.com/learn/1054", "title": "走進Python量化交易--入門篇", "image_url": "http://img2.sycdn.imooc.com/5ba2386600013d3705980337-240-135.jpg", "student_num": "", "introduction": "從基礎學習開啟Python量化交易之路。", "image_path": ["full/c5a51605223816405089ed233953bacc53b226c6.jpg"]}

{"url": "http://www.imooc.com/learn/1054", "title": "走進Python量化交易--入門篇", "image_url": "http://img2.sycdn.imooc.com/5ba2386600013d3705980337-240-135.jpg", "student_num": "", "introduction": "從基礎學習開啟Python量化交易之路。", "image_path": ["full/26d5e7b23aa0cfe31ccee6b25fddaede99131ade.jpg"]}

{"url": "http://www.imooc.com/learn/1054", "title": "走進Python量化交易--入門篇", "image_url": "http://img2.sycdn.imooc.com/5ba2386600013d3705980337-240-135.jpg", "student_num": "", "introduction": "從基礎學習開啟Python量化交易之路。", "image_path": ["full/4c0c172fd04de6015922608e2113f6138fe88456.jpg"]}