基於 Python 的 Scrapy 爬蟲入門:頁面提取

目錄


下面建立一個爬蟲項目,以圖蟲網爲例抓取圖片。python

1、內容分析

打開 圖蟲網,頂部菜單「發現」 「標籤」裏面是對各類圖片的分類,點擊一個標籤,好比「美女」,網頁的連接爲:https://tuchong.com/tags/美女/,咱們以此做爲爬蟲入口,分析一下該頁面:web

打開頁面後出現一個個的圖集,點擊圖集可全屏瀏覽圖片,向下滾動頁面會出現更多的圖集,沒有頁碼翻頁的設置。Chrome右鍵「檢查元素」打開開發者工具,檢查頁面源碼,內容部分以下:數據庫

<div class="content">
    <div class="widget-gallery">
        <ul class="pagelist-wrapper">
            <li class="gallery-item...

能夠判斷每個li.gallery-item是一個圖集的入口,存放在ul.pagelist-wrapper下,div.widget-gallery是一個容器,若是使用 xpath 選取應該是://div[@class="widget-gallery"]/ul/li,按照通常頁面的邏輯,在li.gallery-item下面找到對應的連接地址,再往下深刻一層頁面抓取圖片。json

可是若是用相似 Postman 的HTTP調試工具請求該頁面,獲得的內容是:segmentfault

<div class="content">
    <div class="widget-gallery"></div>
</div>

也就是並無實際的圖集內容,所以能夠判定頁面使用了Ajax請求,只有在瀏覽器載入頁面時纔會請求圖集內容並加入div.widget-gallery中,經過開發者工具查看XHR請求地址爲:數組

https://tuchong.com/rest/tags/美女/posts?page=1&count=20&order=weekly&before_timestamp=

參數很簡單,page是頁碼,count是每頁圖集數量,order是排序,before_timestamp爲空,圖蟲由於是推送內容式的網站,所以before_timestamp應該是一個時間值,不一樣的時間會顯示不一樣的內容,這裏咱們把它丟棄,不考慮時間直接從最新的頁面向前抓取。瀏覽器

請求結果爲JSON格式內容,下降了抓取難度,結果以下:app

{
  "postList": [
    {
      "post_id": "15624611",
      "type": "multi-photo",
      "url": "https://weishexi.tuchong.com/15624611/",
      "site_id": "443122",
      "author_id": "443122",
      "published_at": "2017-10-28 18:01:03",
      "excerpt": "10月18日",
      "favorites": 4052,
      "comments": 353,
      "rewardable": true,
      "parent_comments": "165",
      "rewards": "2",
      "views": 52709,
      "title": "微風不燥  秋意正好",
      "image_count": 15,
      "images": [
        {
          "img_id": 11585752,
          "user_id": 443122,
          "title": "",
          "excerpt": "",
          "width": 5016,
          "height": 3840
        },
        {
          "img_id": 11585737,
          "user_id": 443122,
          "title": "",
          "excerpt": "",
          "width": 3840,
          "height": 5760
        },
        ...
      ],
      "title_image": null,
      "tags": [
        {
          "tag_id": 131,
          "type": "subject",
          "tag_name": "人像",
          "event_type": "",
          "vote": ""
        },
        {
          "tag_id": 564,
          "type": "subject",
          "tag_name": "美女",
          "event_type": "",
          "vote": ""
        }
      ],
      "favorite_list_prefix": [],
      "reward_list_prefix": [],
      "comment_list_prefix": [],
      "cover_image_src": "https://photo.tuchong.com/443122/g/11585752.webp",
      "is_favorite": false
    }
  ],
  "siteList": {...},
  "following": false,
  "coverUrl": "https://photo.tuchong.com/443122/ft640/11585752.webp",
  "tag_name": "美女",
  "tag_id": "564",
  "url": "https://tuchong.com/tags/%E7%BE%8E%E5%A5%B3/",
  "more": true,
  "result": "SUCCESS"
}

根據屬性名稱很容易知道對應的內容含義,這裏咱們只需關心 postlist 這個屬性,它對應的一個數組元素即是一個圖集,圖集元素中有幾項屬性咱們須要用到:dom

  • url:單個圖集瀏覽的頁面地址
  • post_id:圖集編號,在網站中應該是惟一的,能夠用來判斷是否已經抓取過該內容
  • site_id:做者站點編號 ,構建圖片來源連接要用到
  • title:標題
  • excerpt:摘要文字
  • type:圖集類型,目前發現兩種,一種multi-photo是純照片,一種text是文字與圖片混合的文章式頁面,兩種內容結構不一樣,須要不一樣的抓取方式,本例中只抓取純照片類型,text類型直接丟棄
  • tags:圖集標籤,有多個
  • image_count:圖片數量
  • images:圖片列表,它是一個對象數組,每一個對象中包含一個img_id屬性須要用到

根據圖片瀏覽頁面分析,基本上圖片的地址都是這種格式: https://photo.tuchong.com/{site_id}/f/{img_id}.jpg ,很容易經過上面的信息合成。scrapy

2、建立項目

  1. 進入cmder命令行工具,輸入workon scrapy 進入以前創建的虛擬環境,此時命令行提示符前會出現(Scrapy) 標識,標識處於該虛擬環境中,相關的路徑都會添加到PATH環境變量中便於開發及使用。
  2. 輸入 scrapy startproject tuchong 建立項目 tuchong
  3. 進入項目主目錄,輸入 scrapy genspider photo tuchong.com 建立一個爬蟲名稱叫 photo (不能與項目同名),爬取 tuchong.com 域名(這個須要修改,此處先輸個大概地址),的一個項目內能夠包含多個爬蟲

通過以上步驟,項目自動創建了一些文件及設置,目錄結構以下:

(PROJECT)
│  scrapy.cfg
│
└─tuchong
    │  items.py
    │  middlewares.py
    │  pipelines.py
    │  settings.py
    │  __init__.py
    │
    ├─spiders
    │  │  photo.py
    │  │  __init__.py
    │  │
    │  └─__pycache__
    │          __init__.cpython-36.pyc
    │
    └─__pycache__
            settings.cpython-36.pyc
            __init__.cpython-36.pyc
  • scrapy.cfg:基礎設置
  • items.py:抓取條目的結構定義
  • middlewares.py:中間件定義,此例中無需改動
  • pipelines.py:管道定義,用於抓取數據後的處理
  • settings.py:全局設置
  • spiders\photo.py:爬蟲主體,定義如何抓取須要的數據

3、主要代碼

items.py 中建立一個TuchongItem類並定義須要的屬性,屬性繼承自 scrapy.Field 值能夠是字符、數字或者列表或字典等等:

import scrapy

class TuchongItem(scrapy.Item):
    post_id = scrapy.Field()
    site_id = scrapy.Field()
    title = scrapy.Field()
    type = scrapy.Field()
    url = scrapy.Field()
    image_count = scrapy.Field()
    images = scrapy.Field()
    tags = scrapy.Field()
    excerpt = scrapy.Field()
    ...

這些屬性的值將在爬蟲主體中賦予。

spiders\photo.py 這個文件是經過命令 scrapy genspider photo tuchong.com 自動建立的,裏面的初始內容以下:

import scrapy

class PhotoSpider(scrapy.Spider):
    name = 'photo'
    allowed_domains = ['tuchong.com']
    start_urls = ['http://tuchong.com/']

    def parse(self, response):
        pass

爬蟲名 name,容許的域名 allowed_domains(若是連接不屬於此域名將丟棄,容許多個) ,起始地址 start_urls 將從這裏定義的地址抓取(容許多個)
函數 parse 是處理請求內容的默認回調函數,參數 response 爲請求內容,頁面內容文本保存在 response.body 中,咱們須要對默認代碼稍加修改,讓其知足多頁面循環發送請求,這須要重載 start_requests 函數,經過循環語句構建多頁的連接請求,修改後代碼以下:

import scrapy, json
from ..items import TuchongItem

class PhotoSpider(scrapy.Spider):
    name = 'photo'
    # allowed_domains = ['tuchong.com']
    # start_urls = ['http://tuchong.com/']

    def start_requests(self):
        url = 'https://tuchong.com/rest/tags/%s/posts?page=%d&count=20&order=weekly';
        # 抓取10個頁面,每頁20個圖集
        # 指定 parse 做爲回調函數並返回 Requests 請求對象
        for page in range(1, 11):
            yield scrapy.Request(url=url % ('美女', page), callback=self.parse)

    # 回調函數,處理抓取內容填充 TuchongItem 屬性
    def parse(self, response):
        body = json.loads(response.body_as_unicode())
        items = []
        for post in body['postList']:
            item = TuchongItem()
            item['type'] = post['type']
            item['post_id'] = post['post_id']
            item['site_id'] = post['site_id']
            item['title'] = post['title']
            item['url'] = post['url']
            item['excerpt'] = post['excerpt']
            item['image_count'] = int(post['image_count'])
            item['images'] = {}
            # 將 images 處理成 {img_id: img_url} 對象數組
            for img in post.get('images', ''):
                img_id = img['img_id']
                url = 'https://photo.tuchong.com/%s/f/%s.jpg' % (item['site_id'], img_id)
                item['images'][img_id] = url

            item['tags'] = []
            # 將 tags 處理成 tag_name 數組
            for tag in post.get('tags', ''):
                item['tags'].append(tag['tag_name'])
            items.append(item)
        return items

通過這些步驟,抓取的數據將被保存在 TuchongItem 類中,做爲結構化的數據便於處理及保存。

前面說過,並非全部抓取的條目都須要,例如本例中咱們只須要 type="multi_photo 類型的圖集,而且圖片太少的也不須要,這些抓取條目的篩選操做以及如何保存須要在pipelines.py中處理,該文件中默認已建立類 TuchongPipeline 並重載了 process_item 函數,經過修改該函數只返回那些符合條件的 item,代碼以下:

...
    def process_item(self, item, spider):
        # 不符合條件觸發 scrapy.exceptions.DropItem 異常,符合條件的輸出地址
        if int(item['image_count']) < 3:
            raise DropItem("美女太少: " + item['url'])
        elif item['type'] != 'multi-photo':
            raise DropItem("格式不對: " + + item['url'])
        else:
            print(item['url'])
        return item
...

固然若是不用管道直接在 parse 中處理也是同樣的,只不過這樣結構更清晰一些,並且還有功能更多的FilePipelinesImagePipelines可供使用,process_item將在每個條目抓取後觸發,同時還有 open_spiderclose_spider 函數能夠重載,用於處理爬蟲打開及關閉時的動做。

注意:管道須要在項目中註冊才能使用,在 settings.py 中添加:

ITEM_PIPELINES = {
    'tuchong.pipelines.TuchongPipeline': 300, # 管道名稱: 運行優先級(數字小優先)
}

另外,大多數網站都有反爬蟲的 Robots.txt 排除協議,設置 ROBOTSTXT_OBEY = True 能夠忽略這些協議,是的,這好像只是個君子協定。若是網站設置了瀏覽器User Agent或者IP地址檢測來反爬蟲,那就須要更高級的Scrapy功能,本文不作講解。

4、運行

返回 cmder 命令行進入項目目錄,輸入命令:

scrapy crawl photo

終端會輸出全部的爬行結果及調試信息,並在最後列出爬蟲運行的統計信息,例如:

[scrapy.statscollectors] INFO: Dumping Scrapy stats:
{'downloader/request_bytes': 491,
 'downloader/request_count': 2,
 'downloader/request_method_count/GET': 2,
 'downloader/response_bytes': 10224,
 'downloader/response_count': 2,
 'downloader/response_status_count/200': 2,
 'finish_reason': 'finished',
 'finish_time': datetime.datetime(2017, 11, 27, 7, 20, 24, 414201),
 'item_dropped_count': 5,
 'item_dropped_reasons_count/DropItem': 5,
 'item_scraped_count': 15,
 'log_count/DEBUG': 18,
 'log_count/INFO': 8,
 'log_count/WARNING': 5,
 'response_received_count': 2,
 'scheduler/dequeued': 1,
 'scheduler/dequeued/memory': 1,
 'scheduler/enqueued': 1,
 'scheduler/enqueued/memory': 1,
 'start_time': datetime.datetime(2017, 11, 27, 7, 20, 23, 867300)}

主要關注ERRORWARNING兩項,這裏的 Warning 實際上是不符合條件而觸發的 DropItem 異常。

5、保存結果

大多數狀況下都須要對抓取的結果進行保存,默認狀況下 item.py 中定義的屬性能夠保存到文件中,只須要命令行加參數 -o {filename} 便可:

scrapy crawl photo -o output.json # 輸出爲JSON文件
scrapy crawl photo -o output.csv  # 輸出爲CSV文件

注意:輸出至文件中的項目是未通過 TuchongPipeline 篩選的項目,只要在 parse 函數中返回的 Item 都會輸出,所以也能夠在 parse 中過濾只返回須要的項目

若是須要保存至數據庫,則須要添加額外代碼處理,好比能夠在 pipelines.pyprocess_item 後添加:

...
    def process_item(self, item, spider):
        ...
        else:
            print(item['url'])
            self.myblog.add_post(item) # myblog 是一個數據庫類,用於處理數據庫操做
        return item
...

爲了在插入數據庫操做中排除重複的內容,可使用 item['post_id'] 進行判斷,若是存在則跳過。

本項目中的抓取內容只涉及了文本及圖片連接,並未下載圖片文件,如需下載圖片,能夠經過兩種方式:

  1. 安裝 Requests 模塊,在 process_item 函數中下載圖片內容,同時在保存數據庫時替換爲本地圖片路徑。
  2. 使用 ImagePipelines 管道下載圖片,具體使用方法下回講解。
相關文章
相關標籤/搜索