基於管道的持久化儲存
阿新 • • 發佈:2020-12-13
基於管道的持久化儲存
-
scrapy框架中已經為我們專門整合好了高效、便捷的持久化操作功能,我們可以直接使用。先來認識兩個檔案:
- items.py:資料結構模板檔案。定義資料屬性。
- pipelines.py:管道檔案。接收資料(items),進行持久化操作。
-
持久化流程(編碼流程)
- 1.資料解析
- 2.在item類中定義相關的屬性
- 3.將解析到的資料封裝儲存到item物件中
- 4.使用yield關鍵字將items物件提交給pipelines管道進行持久化儲存
- 5.在管道檔案中的process_item方法中接收爬蟲檔案提交過來的資料,編寫持久化儲存的程式碼將item物件中儲存的資料進行持久化儲存
- 6.settings.py配置檔案中開啟管道
-
編寫程式碼
爬蟲檔案.py
import scrapy
from qsbkPro.qsbkPro.items import QsbkproItem
class QsbkSpider(scrapy.Spider):
name = 'qsbk'
#allowed_domains = ['www.XXX.com']
start_urls = ['https://www.qiushibaike.com/text/']
def parse(self, response):
div_list = response. xpath("//div[@class='col1 old-style-col1']/div")
for div in div_list:
author = div.xpath("./div[1]/a[2]/h2/text()")[0].extract()
content = div.xpath("./a[1]/div/span//text()").extract()
content = ''.join(content)
item = QsbkproItem( )
item['author'] = author
item['content'] = content
yield item
items.py
import scrapy
class QsbkproItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
author = scrapy.Field()
content = scrapy.Field()
pipelines.py
- 爬蟲檔案中,解析到的資料封裝在item型別的物件中,這段程式碼是寫在for迴圈當中,提交一次,process_item函式被呼叫一次,所以新建檔案fp的程式碼不能寫在該函式中。
settings.py