1. 程式人生 > >2018 - Python 3.7 爬蟲之 利用 Scrapy 框架 獲取圖片並下載(二)

2018 - Python 3.7 爬蟲之 利用 Scrapy 框架 獲取圖片並下載(二)

一、 通過命令構建一個爬蟲專案

二、定義 item

三、啟用 pipeline 管道

四、編寫爬蟲 Spider

五、執行爬蟲

六、結果檢視


未安裝 Scrapy 框架,見上一篇文章:框架安裝及配置

一、 通過命令構建一個爬蟲專案

注:SinanewsSpider 為專案名

scrapy startproject SinanewsSpider

成功建立後的目錄如下:

這些檔案主要是:
scrapy.cfg: 專案配置檔案
SinanewsSpider/: 專案python模組, 程式碼將從這裡匯入
SinanewsSpider/items.py: 專案items檔案
SinanewsSpider/pipelines.py: 專案管道檔案
SinanewsSpider/settings.py: 專案配置檔案
SinanewsSpider/spiders: 放置spider的目錄

二、定義 item

編輯 settings.py 檔案,定義兩個資料存放的容器( items 是將要裝載抓取的資料的容器 )

# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html

import scrapy

class SinanewsspiderItem(scrapy.Item): #定義資料項類,從scrapy.Item繼承
    # define the fields for your item here like:
    # name = scrapy.Field()
    addr = scrapy.Field()
    name = scrapy.Field()
    pass

三、啟用 pipeline 管道

編輯 settings.py 檔案,新增如下程式碼:

BOT_NAME = 'SinanewsSpider'

SPIDER_MODULES = ['SinanewsSpider.spiders']
NEWSPIDER_MODULE = 'SinanewsSpider.spiders'

ROBOTSTXT_OBEY = True

ITEM_PIPELINES = {
    'SinanewsSpider.pipelines.SinanewsspiderPipeline': 300,
}

四、編寫爬蟲 Spider

新建 SinanewsSpider.py 檔案,Scrapy 框架已經幫助我們定義好了基礎爬蟲,只需要從 scrapy.spider 繼承,並重寫相應的解析函式 parse 即可。

注:案例使用的網站是 www.xiaohuar.com

# -*- coding: utf-8 -*-
# 匯入爬蟲框架
import scrapy
# 匯入item中結構化資料模板
from SinanewsSpider.items import SinanewsspiderItem

import urllib.request
import time
import win32api,win32con
import os

class SinanewsSpider(scrapy.Spider):
    # 爬蟲名稱,唯一
    name = 'SinanewsSpider'
    # 允許訪問的域
    allowed_domains = ['xiaohuar.com']
    # 初始URL
    start_urls = [
        'http://www.xiaohuar.com/2014.html'
    ]

    def parse(self, response):
        # 獲取所有圖片的a標籤
        allPics = response.xpath('//div[@class="img"]/a')
        # 判斷檔案是否存在
        if not os.path.exists(get_desktop() + '\\TP'):
            os.mkdir(get_desktop() + '\\TP')
        for pic in allPics:
            # 分別處理每個圖片,取出名稱及地址
            item = SinanewsspiderItem()
            name = pic.xpath('./img/@alt').extract()
            # 沒有這個屬性就不取值
            if name.__len__() != 0:
                name = name[0]
            addr = pic.xpath('./img/@src').extract()
            # 沒有這個屬性就不取值
            if addr.__len__() != 0:
                addr = addr[0]
            # 沒有字首加字首
            if 'http://www.xiaohuar.com' not in addr:
                addr = 'http://www.xiaohuar.com' + addr
            # 將資料存入到資料項
            item['name'] = name
            item['addr'] = addr
            # 下載並儲存到桌面的TP資料夾中
            urllib.request.urlretrieve(addr, get_desktop() + "\\TP\\" + str(round(time.time() * 1000)) + '.jpg')
            print(addr, "下載成功")
            # 返回爬取到的資料
            yield item

# 獲得桌面路徑
def get_desktop():
    key =win32api.RegOpenKey(win32con.HKEY_CURRENT_USER,r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders',0,win32con.KEY_READ)
    return win32api.RegQueryValueEx(key,'Desktop')[0]

五、執行爬蟲

scrapy crawl SinanewsSpider

六、結果檢視