Scrapy框架的基本使用

scrapy框架簡介

Scrapy是用純Python實現一個爲了爬取網站數據、提取結構性數據而編寫的應用框架,用途非常廣泛

框架的力量,用戶只需要定製開發幾個模塊就可以輕鬆的實現一個爬蟲,用來抓取網頁內容以及各種圖片,非常之方便

scrapy架構圖

 

l  crapy Engine(引擎): 負責Spider、ItemPipeline、Downloader、Scheduler中間的通訊,信號、數據傳遞等。

 

l  Scheduler(調度器): 它負責接受引擎發送過來的Request請求,並按照一定的方式進行整理排列,入隊,當引擎需要時,交還給引擎。

 

l  Downloader(下載器):負責下載Scrapy Engine(引擎)發送的所有Requests請求,並將其獲取到的Responses交還給Scrapy Engine(引擎),由引擎交給Spider來處理,

 

l  Spider(爬蟲):它負責處理所有Responses,從中分析提取數據,獲取Item字段需要的數據,並將需要跟進的URL提交給引擎,再次進入Scheduler(調度器),

 

l  Item Pipeline(管道):它負責處理Spider中獲取到的Item,並進行進行後期處理(詳細分析、過濾、存儲等)的地方

 

l  Downloader Middlewares(下載中間件):你可以當作是一個可以自定義擴展下載功能的組件。

 

l  Spider Middlewares(Spider中間件):你可以理解爲是一個可以自定擴展和操作引擎和Spider中間通信的功能組件(比如進入Spider的Responses;和從Spider出去的Requests)

 

 

新建scrapy項目

1、創建爬蟲項目,命令:scrapy startproject 項目名稱

2、創建爬蟲文件,命令:scrapy genspider 文件名稱 域名

創建完成後會自動生成一些文件

目標網站分析需要提取的數據,在item.py文件中添加字段

Item 定義結構化數據字段,用來保存爬取到的數據,有點像Python中的dict,但是提供了一些額外的保護減少錯誤

 

基本案例:

使用scrapy框架爬取quote.xxx 網站, 爬取裏面的所有text, author,tag信息, 並保存到Mongodb數據庫中  

步驟:

  1. 1.      scrapy startproject quotetest  利用scrapy命令常見一個項目,名稱是quotetest
  2. 2.      scrapy genspider quote quotes.toscrape.com 進入cd quotetest 目錄裏面,創建文件名稱是quote的,域名是最後的網址,起始爬蟲的網址
  3. 3.       編輯爬蟲的文件quote.py(是使用命令默認生成的)其中parse方法是一個回調方法,起始url請求成功後,會回調這個方法

   

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

    def parse(self, response):
        #用來解析爬取中的方法,默認的回調,來進行解析
        # print(response.text)
        quotes = response.css('.quote')
        for quote in quotes:
            item = QuotetutorialItem()
            text = quote.css('.text::text').extract_first()
            author = quote.css('.author::text').extract_first()
            tags = quote.css('.tags .tag::text').extract()
            item['text'] = text
            item['author'] = author
            item['tags'] = tags
            yield item


        next = response.css('.pager .next a::attr(href)').extract_first()
        url = response.urljoin(next) #絕對的url
        yield scrapy.Request(url=url, callback=self.parse)

 

  1. 4.      配置item.py文件,Item 定義結構化數據字段,用來保存爬取到的數據,有點像Python中的dict,但是提供了一些額外的保護減少錯誤 ,在quote.py中的parse方法中有使用這個類,作爲解析數據的

   

class QuotetutorialItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    #存儲
    text = scrapy.Field()
    author = scrapy.Field()
    tags = scrapy.Field()

 

  1. 5.      配置pipline.py中的類,它負責處理Spider中獲取到的Item,並進行進行後期處理(詳細分析、過濾、存儲等)的地方. 我們需要將text中的內容過長的數據進行截取 結尾使用‘…’來代替,方法如

  

class TextPipline(object):
    def __init__(self):
        self.limit = 50
    def process_item(self, item, spider):
        if item['text']:
            if len(item['text']) > self.limit:
                item['text'] = item['text'][:self.limit].rstrip() + '...'
                return item
        else:
            return DropItem('Missing Text')

 

  1. 6.      配置pipline.py中的類,進行進行後期存儲處理,將數據保存到mongodb中, 方法如下

  

class MongoPipline(object):
    def __init__(self, mongo_url, mongo_db):
        self.mongo_url = mongo_url
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        #從setting裏面拿到相應的配置信息
        return cls(
            mongo_url=crawler.settings.get('MONGO_URL'),
            mongo_db = crawler.settings.get('MONGO_DB')
        )
    def open_spider(self, spider):
        self.client = pymongo.MongoClient(self.mongo_url)
        self.db= self.client[self.mongo_db]
    def process_item(self, item, spider):
        name = item.__class__.__name__
        self.db[name].insert(dict(item))
        return item
    def close_spider(self, spider):
        self.client.close()

 

使用類方法,將配置文件中的變量配置到類中進行初始化  初始化mongodb類, 並使用方法process_item進行保存數據到mongodb中  ,最後執行關閉操作   

 

注意settings文件中需要設置如下, 否則無法知道pipline的處理

 

Setttings文件中,設置好mongodb的配置

ITEM_PIPELINES = {
   'quotetutorial.pipelines.TextPipline': 300,
    'quotetutorial.pipelines.MongoPipline': 400,
}


MONGO_URL = 'localhost'
MONGO_DB  = 'quotertutors'

 

 

參考網址:https://www.jianshu.com/p/8e78dfa7c368

 

Scrapy中選擇器的用法:

選擇器的用法 這裏介紹 3中 css xpath 還有  re

 

 

選擇器的用法  

https://docs.scrapy.org/en/latest/topics/selectors.html?highlight=using%20selectors#id1

scrapy shell https://docs.scrapy.org/en/latest/_static/selectors-sample1.html

#進入交互模式

網頁的源代碼是

<html>
 <head>
  <base href='http://example.com/' />
  <title>Example website</title>
 </head>
 <body>
  <div id='images'>
   <a href='image1.html'>Name: My image 1 <br /><img src='image1_thumb.jpg' /></a>
   <a href='image2.html'>Name: My image 2 <br /><img src='image2_thumb.jpg' /></a>
   <a href='image3.html'>Name: My image 3 <br /><img src='image3_thumb.jpg' /></a>
   <a href='image4.html'>Name: My image 4 <br /><img src='image4_thumb.jpg' /></a>
   <a href='image5.html'>Name: My image 5 <br /><img src='image5_thumb.jpg' /></a>
  </div>
 </body>
</html>

 

 

練習項(CSS):

  1. 查看title的內容
In [88]: response.css('title::text').extract_first()

Out[88]: 'Example website'

 

  1. 查看a標籤下的內容
In [91]: response.css('a::text').extract()

Out[91]:

['Name: My image 1 ',

 'Name: My image 2 ',

 'Name: My image 3 ',

 'Name: My image 4 ',

 'Name: My image 5 ']

 

  1. 查看a標籤下面img標籤對應的屬性src的內容
In [93]: response.css('a img::attr(src)').extract()

Out[93]:

['image1_thumb.jpg',

 'image2_thumb.jpg',

 'image3_thumb.jpg',

 'image4_thumb.jpg',

 'image5_thumb.jpg']

 

  1. 查看a標籤href屬性包含image的下的內容
In [100]: response.css('a[href*=image]::text').extract()

Out[100]:

['Name: My image 1 ',

 'Name: My image 2 ',

 'Name: My image 3 ',

 'Name: My image 4 ',

 'Name: My image 5 ']

 

 

 

 

 

 

 

練習題(xpath):

1.    查看title的內容

In [105]: response.xpath('//title/text()').extract_first()

Out[105]: 'Example website'

 

2.    查看a標籤下的內容

In [107]: response.xpath('//a/text()').extract()

Out[107]:

['Name: My image 1 ',

 'Name: My image 2 ',

 'Name: My image 3 ',

 'Name: My image 4 ',

 'Name: My image 5 ']

 

3.    查看a標籤下面img標籤對應的屬性src的內容

In [112]: response.xpath('//a/img/@src').extract()

Out[112]:

['image1_thumb.jpg',

 'image2_thumb.jpg',

 'image3_thumb.jpg',

 'image4_thumb.jpg',

 'image5_thumb.jpg']

 

4.    查看a標籤href屬性包含image的下的內容

In [115]: response.xpath('//a[contains(@href, "image")]/text()').extract()

Out[115]:

['Name: My image 1 ',

 'Name: My image 2 ',

 'Name: My image 3 ',

 'Name: My image 4 ',

 'Name: My image 5 ']

 

 

練習題(re):

  1. 查詢a標籤下的內容,並利用re模塊查看Name:後面的內容(使用css選擇器)
In [116]: response.css('a::text').re('Name:(.*)')

Out[116]:

[' My image 1 ',

 ' My image 2 ',

 ' My image 3 ',

 ' My image 4 ',

 ' My image 5 ']

 

  1. 查詢a標籤下的內容,並利用re模塊查看Name:後面的內容(使用xpath選擇器)
In [117]: response.xpath('//a/text()').re('Name:(.*)')

Out[117]:

[' My image 1 ',

 ' My image 2 ',

 ' My image 3 ',

 ' My image 4 ',

 ' My image 5 ']

 

 

 

In [119]: response.xpath('//a/text()').re_first('Name:(.*)').strip()

Out[119]: 'My image 1'

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章