爬蟲系列2 scrapy專案入門案例分析

2021-07-13 06:48:34 字數 3035 閱讀 1940

本文從乙個基礎案例入手,較為詳細的分析了scrapy專案的建設過程(在官方文件的基礎上做了調整)。主要內容如下:

0、準備工作

1、scrapy專案結構

2、編寫spider

3、編寫item.py

4、編寫pipelines.py

5、設定settings.py

6、執行spider

安裝scrapy,在cmd中輸入命令(windows)即可完成:pipinstall scrapy

建立scrapy專案,在cmd中輸入命令(windows):scrapystart project tutorial。專案的目錄結構如下。

tutorial/

scrapy.cfg

tutorial/

__init__.py

items.py

pipelines.py

settings.py

spiders/

__init__.py

myspider.py

一般來說,要完成乙個能用的scrapy爬蟲,需要編寫或者配置的檔案包括myspider.py、settings.py、item.py和pipeline.py。其中myspider.py在spider目錄下,是核心的爬蟲檔案;settings.py用來配置爬取時間間隔等引數;item.py用來定義資料提取的專案;pipeline.py和item.py配合使用,用來輔助完成爬取資料的格式化輸出。

spider檔案可以自行命名,此處的爬蟲檔名為dmoz_spider.py。該檔案定義了爬蟲名稱、目標**、執行函式等。以下是spider**示例,它定義了爬蟲名稱name,允許執行域allowed_domain,起始爬取頁面**start_urls,parse(self, response)是spider必須實現的介面,負責提取頁面中title、href和desc等屬性,詳細內容可參考以下**注釋。     

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

import scrapy

from tutorial.itemsimport dmozitem

classdmozspider(scrapy.spider):

name = 'dmoz' #爬蟲名,供命令scrapycrawl domz使用

allowed_domain = 'dmoz.org' #允許爬蟲執行的域

start_urls =['',

'']#爬取url

def parse(self, response): #頁面解析函式,這裡必須為parse()

for sel in response.xpath('//ul/li'):

item = dmozitem() #在items.py中定義的需解析專案

item['title'] =sel.xpath('a/text()').extract() #使用xpath提取特定屬性

item['href'] =sel.xpath('a/@href').extract()

item['desc'] =sel.xpath('text()').extract()

yield item

應該引起注意的是:item.py和dmoz_spider.py是相互關聯的;item.py中定義的title、link和desc,在dmoz_spider.py中將會用到。

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

# 定義爬取物件屬性

import scrapy

classdmozitem(scrapy.item):

title = scrapy.field()

link = scrapy.field()

desc = scrapy.field()

pass

pipelines是scrapy提供的資料匯出手段之一,通過pipelines可以進行複雜的資料匯出操作,包括將資料匯出到json檔案或者資料庫。pipelines.py中必須實現process_item(self, item, spider)介面,用於處理需要儲存的item資料,其中spider為所定義的爬蟲dmoz。

pipelines.py**見下文,其中技術要點有:

1)使用codecs.open()以給定的模式mode和編碼encoding開啟檔案,檔案不存在時則新建。

2)使用json.dumps()將dict轉化為json格式的字串,如果ensure_ascii設為false,則返回值將會是unicode格式。 

import json

import codecs

#寫pipeline時需要注意編碼問題的處理

class dmozpipeline(object):

def __init__(self):

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

def process_item(self, item, spider):

line = json.dumps(dict(item), ensure_ascii=false)+'\n'# ensure_ascii=false很重要

self.file.write(line)

return item

def close_spider(self,spider):

self.file.close()

補充:另一種替代的資料匯出方式是:在cmd中執行scrapycrawl dmoz –o abc.json,其中abc.json為匯出檔案。採用該方式無需配置pipeline,因為程式執行過程中不會用到。

通過settings告知spider將啟用pipeline,其餘用預設設定就好了。

item_pipelines =

在cmd中執行scrapycrawl dmoz,可以將爬取的所有結果以json格式匯出到名為dmoz.json的檔案中,檔名可以在pipeline.py中修改。

至此,乙個完整的scrapy爬蟲專案就算完成了。

2 scrapy使用步驟

本篇介紹scrapy的使用步驟。scrapy是python的乙個框架,可以通過安裝python包的形式安裝,必須先安裝python。安裝python2.7 安裝pip 安裝lxml 抽取資料 安裝openssl 網頁訪問認證 安裝scrapy create a project define item...

scrapy 爬蟲入門(1)

pip install scrapy 就是這麼簡單 scrapy startproject words 會建立乙個words的專案目錄結構 words scrapy.cfg 專案的配置檔案 words 專案 init py items.py 專案的item檔案 pipelines.py 專案的pip...

Scrapy搭建爬蟲專案

1.進入到conda環境中,執行conda create name scrapy env python 3.6.5 scrapy建立乙個關於scrapy專案的虛擬環境。只需要建立乙個scrapy的虛擬環境就可以,不需要每次都建立 2.執行conda activate scrapy env切換到 sc...